The following throws an exception “The process cannot access the file 'D:\MyDir\First.txt' because it is being used by another process.“
static void Main(string[] args)
{
Directory.CreateDirectory(@"D:\MyDir");
File.Create(@"D:\MyDir\First.txt");
File.WriteAllText(@"D:\MyDir\First.txt", "StackOverflow.com");
}
However following works:
using (File.Create(@"D:\MyDir\First.txt"))
{
}
or
File.Create(@"D:\MyDir\First.txt").Close();
Why? What in File.Create needs to be closed?
File.Createis doing more than you think here. It’s not just creating the file, it’s also returning an active stream to the file. However, you’re not doing anything with that stream. Theusingblock in your latter example closes that stream by disposing it.Note also that this is a significant clue about the return value:
(It actually wasn’t intuitive to me when I first read your question, but looking back at it this line of code actually says it all.)
Your next step, calling
File.WriteAllTextalso does more than you think. According to the documentation, it:So it would seem that your
File.Createcall isn’t really needed here anyway.