-
File close
Code:
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();
}
}
-
Re: File close
Why are you using the class finalizer to close the file?
Check out the 'using' block syntax.
-
Re: File close
Hi, I found about Finalizer and rewrote as :
~FileDemo()
{
w.Close();
r.Close();
f.Close();
}
but still having same problem
-
Re: File close
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 documentation in msdn.
-
Re: File close
sure, thats a helpful tip, going forward will follow that