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

Brett picture Brett · May 6, 2010 · Viewed 179.5k times · Source

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

Carsen Daniel Yates picture Carsen Daniel Yates · Jul 27, 2011
    File.Create(FilePath).Close();
    File.WriteAllText(FileText);

I want to update this answer to say that this is not really the most efficient way to write all text. You should only use this code if you need something quick and dirty.

I was a young programmer when I answered this question, and back then I thought I was some kind of genius for coming up with this answer.