Reputation: 495
i want to know if can i re-open a handle after FileStream close it ??
this is mycode
static void Main(string[] args)
{
string path = "Hello";
SafeFileHandle handle = File.Open(path, FileMode.OpenOrCreate).SafeFileHandle;
using (FileStream fs1 = new FileStream(handle, FileAccess.ReadWrite))
{
// do some work
}
using (FileStream fs2 = new FileStream(handle, FileAccess.ReadWrite))
{
// do some work
}
Console.ReadKey();
}
i get error " the handle has been closed " in declaring fs2 .
Thanks :)
Upvotes: 0
Views: 378
Reputation: 29051
No. The handle is acquired when the file is opened, and becomes invalid once it is closed. Just keep the file open.
The OS keeps a map of handles - really, just integer IDs - for any resource that is allocated. When you release (or, in this case, close) the resource, that map entry is removed, and any locks that were acquired are freed. Any further calls with that handle will start with a map search for the handle, which has been removed, so...
Not going to work. Either re-open the file, or find a way to keep it open if necessary. Really, though - I despise implementations that lock files. The vast majority of apps that do this really don't have to, and it just causes problems. Open the file, load the data, close the file, modify the data and dump it as necessary. There are very, very few valid reasons to keep a file open for longer than a single function call.
Upvotes: 1