Getting exception while Creation a text file in Appdata folder, its saying File it is being used by another process

269 views Asked by At

I am writing a text file in Appdata folder, I am creating a folder and creating a text file and in next line I am writing text into the file through StreamWriter. But here I am getting following exception.

The process cannot access the file 'C:\sdfdfg\sdfsd\AppData\Roaming\MyFolder\myFile.txt' because it is being used by another process.

This exception I am getting when I create file, if I run app second time than the app is writing the text into same file.

My Code is following

StringBuilder sb=new StringBuilder();
if (!File.Exists(filePath))
{
     File.Create(filePath);
     sb.AppendLine(line);
     using (StreamWriter writer = new StreamWriter(filePath, true))
     {
         writer.Write(sb.ToString());
         writer.Close();
     }
}

I tried another function of File, File.WriteAllText(filePath, textToWrite); but it is also performing same way as above StreamWriter is behaving.

1

There are 1 answers

1
Willem van Rumpt On BEST ANSWER

The simplest solution is to just leave out File.Create().

The constructor you're using for your StreamWriter will already create the file if it doesn't exist.

Another option is to pass the FileStream that File.Create() returns into an appropriate constructor of StreamWriter.