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();
}
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.
See more on this question at Stackoverflow