Hi all,
Can anyone explain to me why this:
File.Create("foamy.txt");
File.ReadAllLines("foamy.txt");produces a System.IOException and this:
using(StreamWriter sw = new StreamWriter("foamy.txt"))
{
}
File.ReadAllLines("foamy.txt");does not? Why isn't the file-handle closed when using the File.Create method?

1 answers
The problem is that File.Create creates a FileStream object with a FileShare value of None. Consequently, no other code can access the file until the original FileStream has been closed and the file handle released.
To remedy this, use:
FileStream fs = File.Create("foamy.txt");fs.Close();
File.ReadAllLines("foamy.txt");
Using a StreamWriter to create the file doesn't give you this problem, because the using statement automatically disposes of the stream and releases the file handle.
answered one year ago by:
17279
2499
Silly me, I hadn't even checked the return type of the Create method *blush* ... So I could actually save a line and do File.Create("foamy.txt").Close(); ?
17279
Yep, you could do it in one line if you prefer.