0

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 :)

Salo7ty
  • 475
  • 5
  • 18

1 Answers1

1

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.

3Dave
  • 28,657
  • 18
  • 88
  • 151
  • okay thanks very much for your caring but can you tell me how to leave the file open :) – Salo7ty Oct 27 '19 at 00:58
  • @ProfSoft "how to leave the file open and..." ?? And what? – 3Dave Oct 27 '19 at 00:58
  • in your first comment you mentioned about " garbdge pointer " what is garbdge pointer ? – Salo7ty Oct 27 '19 at 01:00
  • @ProfSoft Don't worry about that. Basically, it meant that you've released a resource and then tried to use it. Kind of like trying to drive a car that you already sold. Don't keep the file open. Either re-open it, or find way that makes sense. This approach is very bad. – 3Dave Oct 27 '19 at 01:04
  • I do not know what to say thanks very very much :)))))) – Salo7ty Oct 27 '19 at 01:08
  • @ProfSoft Spend a few minutes to formulate a question about *what you are actually trying to accomplish. – 3Dave Oct 27 '19 at 01:18