Ivan Li
Ivan Li

Reputation: 1950

What happens if StreamReader or StreamWriter are not closed?

I'm working on an assignment for a professor that is strict about LOC. For this reason I'd like to do the following:

(new StreamWriter(saveFileDialog.FileName)).Write(textBox.Text);

instead of

StreamWriter sw = new StreamWriter(saveFileDialog.FileName);
sw.Write(textBox.Text);
sw.Close();

In the first example I don't close the stream. Is this ok? Will it cause any security or memory problems?

Upvotes: 4

Views: 4322

Answers (9)

to StackOverflow
to StackOverflow

Reputation: 124696

Maybe your tutor is looking for:

File.WriteAllText(saveFileDialog.FileName, textbox.Text);

It's reasonable to prefer concise code, but not at the expense of readability or correctness.

Upvotes: 8

Antarr Byrd
Antarr Byrd

Reputation: 26061

It would be a memory hazard.

I would always use StreamWriter in a 'using' statement

using(StreamWriter fout = new StreamWriter(saveFileDialog.FileName)
{
    fout.Write(textBox.Text);
}

Upvotes: 0

lboshuizen
lboshuizen

Reputation: 2786

Consider

using( var fout = new StreamWriter(saveFileDialog.FileName){ fout.write(textBox.Text); }

Upvotes: 1

Aghilas Yakoub
Aghilas Yakoub

Reputation: 28970

You can try with using blok in order to clean your no managed object

        using (var streamWriter = new StreamWriter(saveFileDialog.FileName))
        {
            streamWriter.Write(textBox.Text);
        }

Upvotes: 0

Matt Burland
Matt Burland

Reputation: 45135

If you don't close it, you can't guarantee that it'll write out the last piece of data written to it. This is because it uses a buffer and the buffer is flushed when you close the stream.

Second, it will lock the file as open preventing another process from using it.

The safest way to use a filestream is with a using statement.

Upvotes: 3

FosterZ
FosterZ

Reputation: 3911

Any how GC will close it for you. But the thing is until the GC closes that stream you are unnecessary putting on hold to the resources

Upvotes: 0

Nikola Davidovic
Nikola Davidovic

Reputation: 8656

Simplest solution without fout.Close() should be:

        using (StreamWriter fout = new StreamWriter(saveFileDialog.FileName))
        {
            fout.Write(textBox.Text);
        }

Upvotes: 5

Freeman
Freeman

Reputation: 5801

Short answer, the resources allocated for that operation will not be freed not to mention that it could pottentially lock that file.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1499760

You may not get any output, or incomplete output. Closing the writer also flushes it. Rather than manually calling Close at all, I'd use a using statement... but if you're just trying to write text to a file, use a one-shot File.WriteAllText call:

File.WriteAllText(saveFileDialog.FileName, textBox.Text);

Upvotes: 16

Related Questions