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?
The
File.Createmethod creates the file and opens aFileStreamon the file. So your file is already open. You don’t really need the file.Create method at all:The boolean in the
StreamWriterconstructor will cause the contents to be appended if the file exists.