2

What will happen to an open FileStream if it is not close due to a program crash? Will it be close automatically? I can't enclose it in a try catch or using because I am doing something with the file. It's like I open the file with an Open button.

private void button1_Click(object sender, RoutedEventArgs e)
{
    fs = new FileStream("Test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);          
}

Then I do something with it. Then in the Exit or closing of the application I execute close.

fs.Close();

But what if something happens in between, like a program crash. Will the file be not accessible since it is not close properly? Thanks.

rpb
  • 23
  • 3
  • The handle will be automatically closed by the operating system. – Matthew Aug 14 '13 at 02:15
  • Thanks Matthew.. any links I can give to my boss as a proof? :) – rpb Aug 14 '13 at 03:10
  • As you open the FileStream with read/write access, I assume that you are writing data to the file. When your program crashes during such a write operation you may well leave the file in a corrupted state. – Clemens Aug 14 '13 at 06:15

2 Answers2

3

Actually we cannot know what will happen in such a situation. MSDN says about the FileStream Class that

If a process terminates with part of a file locked or closes a file that has outstanding locks, the behavior is undefined.

t3chb0t
  • 16,340
  • 13
  • 78
  • 118
0

It's hard to find exactly what Windows will do when an application exits, either intentionally or otherwise.

The Terminating a Process article on MSDN describes what happens when a process is terminated, most notably.

Any remaining threads in the process are marked for termination.
Any resources allocated by the process are freed.
All kernel objects are closed.
The process code is removed from memory.
The process exit code is set.
The process object is signaled.

Slightly off-topic, but in your particular piece of code, FileStream implements IDisposable, so you should research on the using keyword for information about deterministic resource clean-up.

Matthew
  • 24,703
  • 9
  • 76
  • 110