Click to See Complete Forum and Search --> : File close


srihariacha
April 16th, 2008, 12:05 AM
using System;
using System.IO;

class Program
{
static void Main(string[] args)
{
FileDemo d = new FileDemo();
d.Manipulate();
Console.ReadLine();
}
}

class FileDemo
{
FileStream f;
StreamReader r;
StreamWriter w;

public FileDemo()
{
f = new FileStream(@"E:\sri.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
w = new StreamWriter(f);
r = new StreamReader(f);
}

public void Manipulate()
{
w.Write("Hi");
Console.WriteLine("Successfully written");
}

~FileDemo()
{
f.Dispose();
w.Dispose();//this program triggers exception "cannot access closed file"
r.Dispose();
}
}

Arjay
April 16th, 2008, 01:07 AM
Why are you using the class finalizer to close the file?

Check out the 'using' block syntax.

srihariacha
April 16th, 2008, 01:19 AM
Hi, I found about Finalizer and rewrote as :
~FileDemo()
{
w.Close();
r.Close();
f.Close();
}

but still having same problem

Arjay
April 16th, 2008, 02:04 AM
The first thing to do when you post code is to use code tags (which are [ CODE] code here [ /CODE] minus the spaces).

You can see an example of the using block in the FileStream class (http://msdn2.microsoft.com/en-us/library/system.io.filestream(VS.80).aspx) documentation in msdn.

srihariacha
April 16th, 2008, 02:23 AM
sure, thats a helpful tip, going forward will follow that