private void buttonAdd_Click(object sender, EventArgs e)
{
string path = @"comics.txt";
if (!File.Exists(path))
{
var myComicsFile = File.Create(path);
myComicsFile.Close();
FileStream file = new FileStream("comics.txt", FileMode.Open, FileAccess.ReadWrite);
TextWriter write = new StreamWriter(path);
}
else if (File.Exists(path))
{
FileStream file = new FileStream("comics.txt", FileMode.Open, FileAccess.ReadWrite);
TextWriter write = new StreamWriter(path);
}
}
I keep getting the error System.IO.IOException: 'The process cannot access the file because it is being used by another process' I thought I had fixed it by closing the file after i created it the opening it but i get the error still. Not sure what the correct solution is. Any help would be greatly appreciated.
Firstly, there is no need to create a file empty and open it, instead use the appropriate FileMode
Instead
OpenOrCreate
Specifies that the operating system should open a file if it exists; otherwise, a new file should be created. If the file is opened with FileAccess.Read, Read permission is required. If the file access is FileAccess.Write, Write permission is required. If the file is opened with FileAccess.ReadWrite, both Read and Write permissions are required.
When you use a BCL method always check the documentation for clues about how to use it, in-particular look for if something supports IDisposable
if it does ALWAYS use a using
statement when you can
using Statement (C# Reference)
Provides a convenient syntax that ensures the correct use of IDisposable objects.
in short you could have just done this
using (var file = new FileStream("comics.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite)
using(var TextWriter write = new StreamWriter(file))
{
// stuff here
}
Basically, when using
a using statement with a stream derivative, it closes and disposes any unmanaged resources like file handles. in your case, you have left the File Handle dangling and hence your problem