Hi,
I have the following code:
Will the following work exactly the same?Code:if (!File.Exists(path))
{
FileStream newFile = File.Create(path);
newFile.Dispose();
}
Thanks :wave:Code:if (!File.Exists(path))
{
File.Create(path).Dispose();
}
Printable View
Hi,
I have the following code:
Will the following work exactly the same?Code:if (!File.Exists(path))
{
FileStream newFile = File.Create(path);
newFile.Dispose();
}
Thanks :wave:Code:if (!File.Exists(path))
{
File.Create(path).Dispose();
}
It is the same.
going to assume you're trying to delete the file though. If that is the case just use File.Delete(path).
No, I'm creating an empty file.
First I used just File.Create(path), and I didn't realize that it returns the filestream created and leaves it open.
So to close the file I figured I'd use Dispose(), but I might be totally mistaken with the usage.
Why do you need to create an empty file in the first place? Can't you just let the framework create it automatically when you start writing to it?
Well you actually have an excellent point there :p
This is an old piece of code I had lying around that uses the StreamWriter directly (as in 'new StreamWriter(path)'), which requires the file to exist.
At that time I probably didn't realize that I could use a FileStream object first and do that...
And that isn't even true...
The StreamWriter doesn't throw FileNotFound exceptions.
I'm clueless why I actually did that check... Well, better to be safe than sorry.
But I guess I can Dispose that code fragment altogether now. :afrog: