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?