-1

If I have a class with the file stream members like so:

public class FooBar
{
    private StreamReader reader;
    private StreamWriter writer;

    public FooBar(string readerFilePath, string writerFilePath)
    {
        reader = new StreamReader(readerFilePath);
        writer = new StreamWriter(writerFilePath);
    }

    ...
}

then how do I close those streams?

It seems that they are closed by default during the class destruction, but then I have to use writer.Flush() which doesn't sound good.

Andrew
  • 197
  • 2
  • 3
  • 16
  • 3
    FooBar should implement IDisposable. See [Implement IDisposable correctly](https://msdn.microsoft.com/en-us/library/ms244737.aspx?f=255&MSPPError=-2147217396) and [Implementing IDisposable correctly](https://stackoverflow.com/a/18337005/2066142) – KiwiPiet Aug 04 '17 at 03:35
  • Still don't get the reason behind the IDisposable Interface if I have to explicitly call the Dispose() method. In my particular case I cannot use the `using` keyword. If I try to call the `writer.Close()` in the destructor (the way I would do it in C++), I get an exception telling that the stream has been already closed. – Andrew Aug 05 '17 at 10:28
  • Maybe I have to learn how the garbage collector works... – Andrew Aug 05 '17 at 10:39
  • [Cleaning Up Unmanaged Resources](https://learn.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged) – Andrew Aug 05 '17 at 10:57

1 Answers1

0

use using block

using(reader = new StreamReader(readerFilePath))
{
  //your code
}

from the below links: Provides a convenient syntax that ensures the correct use of IDisposable objects.

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources. In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

What is the C# Using block and why should I use it?

Vishal Anand
  • 1,431
  • 1
  • 15
  • 32