I have a Windows Forms Application that uses 2 forms, with both writing to separate files (file paths given by inclusion of strings in textboxes on the form).
For form1, I have a number of functions that write data to the file on various different button clicks. This being the case, I used the StreamWriter consoleFile = new StreamWriter(File.OpenWrite(fileName));
method for the first writing to file and StreamWriter consoleFile = File.AppendText(fileName);
for any subsequent ones. This has worked fine.
When it came to implementing the same feature for Form2, the main difference is that all the text is written at once (one function containing four sub-functions to try and keep the code tidy). I went about it like this...
public void writeChecklistToFile()
{
//open new file for writing
StreamWriter checklistFileStart = new StreamWriter(File.OpenWrite(getChecklistFile()));
checklistFileStart.WriteLine("Pre-Anaesthetic Checklist\n");
//sub-functions (one for each section of list)
//append tool used in separate functions
//StreamWriter checklistFile = File.AppendText(getChecklistFile());
writeAnimalDetails();
writeAnimalHistory();
writeAnimalExamination();
writeDrugsCheck();
}
Each of the sub-functions then contains the appendText variable shown above:
public void writeAnimalDetails()
{
StreamWriter checklistFile = File.AppendText(getChecklistFile());
//...
}
Whenever I click the button that calls the main function, it throws an exception on the first File.AppendText() method. It states that the destination file cannot be accessed because it is already being used in another process.
Presumably this has to be the OpenWrite() as it is not used anywhere before that, but I don't understand why this error would occur in my form2 when it doesn't in form1!
If anyone could help me get around this, or can point me in the direction of an easier way to do it, I'd really appreciate that.
Thanks
Mark