I have a windows forms application that should save data to a file. For that I call:
public void SaveVocabulary()
{
string line;
try
{
//create backup of file
File.Copy(ConfigData.Filename, ConfigData.Filename.Replace(".txt", "_backup.txt"), true);
// delete all content
File.Create(ConfigData.Filename).Close();
foreach (VocabularyData vocable in vocList)
{
line = vocable.VocGerman.Replace('|', '/') + "|";
line += vocable.VocEnglish.Replace('|', '/') + "|";
File.AppendAllText(ConfigData.Filename, line + Environment.NewLine);
}
// delete backup
File.Delete(ConfigData.Filename.Replace(".txt", "_backup.txt"));
}
catch (Exception ex)
{
throw new Exception("Error saving Vocabulary: " + ex.Message, ex);
}
}
But every 2nd time I pass the line File.Create(ConfigData.Filename).Close();
the code throws an exception telling me, that I can not access the file because it is used by another process.
Der Prozess kann nicht auf die Datei "C:\Users\some-path\Vocabulary.txt" zugreifen, da sie von einem anderen Prozess verwendet wird.
By documentation the file is closed by File.AppendAllText
.
I also tried to do it with StreamWriter
and close it explicitly. This also threw the same exception.
Also, no one else is using the file. (If you know a way to prevent someone from opening the file for writing while my program is running, please tell me how I can do so.)
Please tell me why this occurs? How can I make sure the file is "free" after saving? So I can save it later a second time.
EDIT: Here is how I load the file:
public List<VocabularyData> LoadVocabulary()
{
try
{
vocList = new List<VocabularyData>();
string[] lines = File.ReadAllLines(GetFileName());
string[] voc;
VocabularyData vocable;
foreach (string line in lines)
{
voc = line.Split('|');
vocable = new VocabularyData();
vocable.VocGerman = voc[0];
vocable.VocEnglish = voc[1];
vocable.CreationDate = DateTime.Parse(voc[2]);
vocable.AssignedDate = DateTime.Parse(voc[3]);
vocable.SuccessQueue = voc[4];
vocable.TimeQueue = voc[5];
vocList.Add(vocable);
}
}
catch (Exception ex)
{
throw new Exception("Error loading Vocabulary: " + ex.Message, ex);
}
return vocList;
}