Link to home
Start Free TrialLog in
Avatar of Priest04
Priest04Flag for Serbia

asked on

StreamWriter Close method

I have a class that has streamwriter object declared on class level. sw is created in the class constructorI have methods that write to a file using sw. Something like:

internal class WriteData
{
    StreamWriter sw;
    // rest of the code
}

internal static class GlobalClass
{
    internal static WriteData writeData;
}

This way GlobalClass is accessible throghout the application. The problem is next:

1) How can I close streamwriter object, I need it to be closed when writeData is going to be destroyed? Calling sw.Close() in writeData destructor doesn't work.
2) is there any way I can check weather streamwriter object is "open", that is, weather something has been written to a file, other than the usual class level boolean variable that will be set to true when the method for writing data has been called?

If this looks confusing, I will explain better what you didn't understand.

Thanks,
Goran
ASKER CERTIFIED SOLUTION
Avatar of Joel Coehoorn
Joel Coehoorn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Priest04

ASKER

>> Actually, because of the 'internal' modifier it's only available in that assembly.  If you move the code to a class library project the rest of the application won't be able to use it.

That was the intention.

Do you know why is sw already closed when object's desctructor is called, but can be called in Dispose method?
Because .Net doesn't do 'destructors'.  When implemented correctly, you can call an IDisposable's Dispose() method as many times as you want without causing an error.
you can open stream inside using block so once you came out of using block it will automatically disposed since it implements IDispose

and inside using block use try catch .. finally and in finally block close stream

so code will be like

using (create streamwriter here sw)
{
try {
...
...
...
}
catch (Exception ex)
{
...
}
finally
{
sw.close();
}
}
No need for the finally block or even to call sw.Close() if it was created with a using statement.  The using statement will make sure it's disposed.

But since the streamwriter is declared as a member of a class, he probably doesn't want a using statement here.