CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5

Thread: File close

  1. #1
    Join Date
    Dec 2007
    Posts
    37

    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.

  2. #2
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    Re: File close

    Why are you using the class finalizer to close the file?

    Check out the 'using' block syntax.

  3. #3
    Join Date
    Dec 2007
    Posts
    37

    Question 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

  4. #4
    Arjay's Avatar
    Arjay is offline Moderator / EX MS MVP Power Poster
    Join Date
    Aug 2004
    Posts
    13,490

    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.

  5. #5
    Join Date
    Dec 2007
    Posts
    37

    Thumbs up 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
  •  





Click Here to Expand Forum to Full Width

Featured