|
-
April 16th, 2008, 12:05 AM
#1
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();
}
}
Last edited by srihariacha; April 16th, 2008 at 02:52 AM.
-
April 16th, 2008, 01:07 AM
#2
Re: File close
Why are you using the class finalizer to close the file?
Check out the 'using' block syntax.
-
April 16th, 2008, 01:19 AM
#3
Re: File close
Hi, I found about Finalizer and rewrote as :
~FileDemo()
{
w.Close();
r.Close();
f.Close();
}
but still having same problem
Last edited by srihariacha; April 16th, 2008 at 01:55 AM.
Reason: getting same error
-
April 16th, 2008, 02:04 AM
#4
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.
-
April 16th, 2008, 02:23 AM
#5
Re: File close
sure, thats a helpful tip, going forward will follow that
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|