C# using Statement when working with Stream's objects

567 views c#
-2

I have the method :

public static void Main()
{
    string path = @"C:\Temp\ProgrammingInCSharp\DirectoryInfo\111.txt";
    using (FileStream fileStream = File.Create(path))
    {
        using (BufferedStream bufferedStream = new BufferedStream(fileStream))
        {
            using (StreamWriter streamWriter = new StreamWriter(bufferedStream))
            {
                streamWriter.WriteLine("A line of text.");
            }
        }
    }
}

Which is using 3 using statements and method works perfectly : create 111.txt and write "A line of text." inside it. But when I change the method to :

public static void Main()
{
    string path = @"C:\Temp\ProgrammingInCSharp\DirectoryInfo\111.txt";
    FileStream fileStream = File.Create(path);
    BufferedStream bufferedStream = new BufferedStream(fileStream);
    StreamWriter streamWriter = new StreamWriter(bufferedStream);
    streamWriter.WriteLine("A line of text.");
}

It just creates 111.txt file but doesn't write "A line of text." inside.

I cannot understand why.

As I read using Statement just call Dispose() method when the object leaves the scope of using Statement. So it should be used to dispose unmanaged code from CLR but why without using Statement I cannot write the text message to my machine's file?

answered question

using doesnt just Dispose, it also closes it - something code block #2 doesnt do

It's likely that because the stream is neither implicitly or explicitly closed it is being abandoned. You should probably add a streamWriter.Flush()

using statements effectively call the dispose method of an object that implements IDispoable. What that dispose method does it up to the implementing object. Yes disposing unmanaged resources is usually involved, but it can do other things, for example, closing a stream

1 Answer

3

There is caching going on in the background. If the file isn't closed properly, the cache doesn't actually get written to the disk. The using statement disposed the object, which closes the file, flushing the cache into the file.

posted this

Have an answer?

JD

Please login first before posting an answer.