locked
read a file at the same it is being written RRS feed

  • Question

  • Hi,

    I am trying to access a log file on a network computer to read the contents but another process writes the file at the same time I try to read it and as a result I get following System.IO.IOException

    "The process cannot access the file "\\servername\sharedfolder\somefile.txt" because it is being used by another process"

    How do I read the file at the same time it is being written by another process??
    I only need to read the last line of the file

    Heres the code
    string fname = @""\\servername\sharedfolder\somefile.txt" ;
    try
    {
    FileStream fs = new FileStream(fname,FileMode.Open,FileAccess.Read );
    StreamReader sr = new StreamReader(fs);
    textbox1.Text = sr.ReadLine();
    }
    catch (System.IO.IOException ex)
    {
     MessageBox.Show(ex.Message.ToString() + ": System.IO.IOException" );
    }


    THanks,

    Thursday, July 7, 2005 6:40 PM

Answers

  • bilalso, you need to specify that other consumers can Share  write access to the file while you're access it. On the FIleStream constructor, choose one which accepts a FileShare, and then specify FIleShare.Write (even better: FileShare.ReadWrite).

    Note: the other process must have given you read access for this to work: I hope that process is under your control. If not, there might not be much else you can do if this doesn't work.

    Regards,
    Kit
    Tuesday, July 19, 2005 6:39 AM

All replies

  • bilalso, you need to specify that other consumers can Share  write access to the file while you're access it. On the FIleStream constructor, choose one which accepts a FileShare, and then specify FIleShare.Write (even better: FileShare.ReadWrite).

    Note: the other process must have given you read access for this to work: I hope that process is under your control. If not, there might not be much else you can do if this doesn't work.

    Regards,
    Kit
    Tuesday, July 19, 2005 6:39 AM
  • Hi - this is exactly what I am trying to do. I tried your code in my situation... but it appears to be needing more setup - what comes before "string fname...." ? In this code (I'm a newby...sorry for the questions) but do you ask to read only the last line of code? And if so, which part says that? I've been racking my brain trying to get data from a txt file generated from another, attached exe into a textbox in my program....

    thanks for anything you might share....

    Tuesday, January 10, 2006 11:12 PM
  • my code will read only one line. ReadLine() only reads one line at a time, if you want to read the whole file run it in a while loop.

     

     

    Wednesday, January 11, 2006 7:44 PM