Brett Brett - 3 months ago 37
C# Question

File being used by another process after using File.Create()

I'm trying to detect if a file exists at runtime, if not, create it. However I'm getting this error when I try to write to it:


The process cannot access the file 'myfile.ext' because it is being used by another process.


string filePath = string.Format(@"{0}\M{1}.dat", ConfigurationManager.AppSettings["DirectoryPath"], costCentre);
if (!File.Exists(filePath))
{
File.Create(filePath);
}

using (StreamWriter sw = File.AppendText(filePath))
{
//write my text
}


Any ideas on how to fix it?

Answer

The File.Create method creates the file and opens a FileStream on the file. So your file is already open. You don't really need the file.Create method at all:

string filePath = @"c:\somefilename.txt";
using (StreamWriter sw = new StreamWriter(filePath, true))
{
    //write to the file
}

The boolean in the StreamWriter constructor will cause the contents to be appended if the file exists.

Comments