0

in my little console app for c# I have to write to a file, and if it is not there i have to create it. It works fine when the file is already created, but when i try and create the file then write to it i get a System.IO.IOException saying the file is in use elsewhere.Here is what i've been using

if (!File.Exists(FilePath))
{
    File.Create(FilePath);
}
FileInfo file = new FileInfo(FilePath);
using (TextWriter tw = new StreamWriter(file.Open(FileMode.Truncate)))
{
    tw.Write(filePresent);
    tw.Close();
}
Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
Mitch
  • 118
  • 9

1 Answers1

7

File.Create returns a FileStream - but you're not closing that.

To be honest, you'd be better off replacing all this code with just:

File.WriteAllText(FilePath, filePresent);

That will create a file if necessary, and truncate it if it already exists. It will close the stream when it's written the data. Simpler all round.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194