3 Replies - 3239 Views - Last Post: 12 January 2014 - 10:13 AM Rate Topic: -----

#1 macroer   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 30-September 13

Why is it important to close a file after reading it?

Posted 11 January 2014 - 09:12 PM

So I recently learned how to open files and I also learned how to put some data from the files into textboxes.

        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog = new OpenFileDialog();

            if (openDialog.ShowDialog() == DialogResult.OK)
            {
                FileStream fileStream = new FileStream(openDialog.FileName, FileMode.Open);

                fileLabel.Text = Path.GetFileName(openDialog.FileName);

                TextReader textReader = new StreamReader(fileStream);

                string line;

                // this code is long so didn't want to post

                fileStream.Close(); // may use
            }
        }



This is my code that I've made so far. Now I'm not asking for any code here but I just want to know why is it important to close a file after opening it to read?

I'm not sure if it applies to other languages but all I know so far is C#. I'm not much of a pro so yeah.

Wouldn't the file close if I closed the application? (Don't know where's the edit button).

Is This A Good Question/Topic? 0
  • +

Replies To: Why is it important to close a file after reading it?

#2 Atli   User is offline

  • Enhance Your Calm
  • member icon

Reputation: 4241
  • View blog
  • Posts: 7,216
  • Joined: 08-June 10

Re: Why is it important to close a file after reading it?

Posted 11 January 2014 - 11:32 PM

In a managed language like C#, it probably would close the file resource when the object responsible for it is destroyed. Which in your case should be when the method ends, since that's when the scope the FileStream and StreamReader objects belong to terminates. (Though I suppose it may have to wait for a memory garbage-cleanup thing to happen. Not to sure about how that's handled in .NET)

However that is not guaranteed of all resources. The built in IO libraries are fairly save, I'd bet, since they are developed by Microsoft themselves, but 3rd party libraries can't be counted on to behave as you'd expect them to; they may not clean up after themselves properly.

It's best to just get into the habit of cleaning up after yourself. Your code will be more reliable, and it'll serve you well if you ever end up building something in a language that doesn't clean up resources automatically, like C/C++.
Was This Post Helpful? 0
  • +
  • -

#3 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7483
  • View blog
  • Posts: 15,510
  • Joined: 16-October 07

Re: Why is it important to close a file after reading it?

Posted 12 January 2014 - 03:28 AM

As a simple design habit, you should always want to keep external resource locks for as short an amount of time as possible. This allows other programs to use those resources and also makes your program more efficient, as it doen't need to track things it's no longer using.

C# actually provides some auto close syntax sugar:
// note, do this before you open the file
// on the principal of shortest possible resource lock
fileLabel.Text = Path.GetFileName(openDialog.FileName);
using(FileStream fileStream = new FileStream(openDialog.FileName, FileMode.Open)) {
    TextReader textReader = new StreamReader(fileStream);
    string line;
} // fileStream will be closed here



There is also a standard pattern for closing (which is why the using thing showed up):
FileStream fileStream = null;
try {
    fileStream = new FileStream(openDialog.FileName, FileMode.Open)) {
    TextReader textReader = new StreamReader(fileStream);
    string line;
} finally {
    fileStream.Close(); // no matter what, close me
}



Consider that using exists and that closing (or disposing of) a resource was important enough to implement such a thing.

Does it always matter? You are correct that you'll probably release everything when the program closes. However, you may not. Even a simple read can bugger you up if you try to write or some other program does. Rather than worrying about if you really have to close in a particular case, just always close and you'll never have to worry.
Was This Post Helpful? 2
  • +
  • -

#4 Curtis Rutland   User is offline

  • (╯□)╯︵ (~ .o.)~
  • member icon


Reputation: 5106
  • View blog
  • Posts: 9,283
  • Joined: 08-June 10

Re: Why is it important to close a file after reading it?

Posted 12 January 2014 - 10:13 AM

Also, if the program crashes it may not release the lock on the file. It's simply good practice, as the others have pointed out, to only utilize a resource for as long as you need to, then release it. Same thing with database connections, same thing with socket IO, same thing for anything that uses system resources.

And even if the runtime or the OS can clean up after you, why make it? Or for that matter, why trust it to? Better to not leave the potential for the problem in the first place.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1