开发者

File Locked by Services (after service code reading the text file)

I have a windows services written in C# .NET. The service is running on a internal timer, every time the interv开发者_如何学Pythonal hits, it will go and try to read this log file into a String.

My issue is every time the log file is read, the service seem to lock the log file. The lock on that log file will continue until I stop the windows service. At the same time the service is checking the log file, the same log file needs to be continuously updated by another program. If the file lock is on, the other program could not update the log file.

Here is the code I use to read the text log file.

        private string ReadtextFile(string filename)
    {
        string res = "";
        try
        {
            System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.StreamReader sr = new System.IO.StreamReader(fs);

            res = sr.ReadToEnd();

            sr.Close();
            fs.Close();
        }
        catch (System.Exception ex)
        {
            HandleEx(ex);
        }

        return res;
    }

Thank you.


I would suggest closing the file in a Finally statement to make sure it gets executed

System.IO.FileStream fs = null;
System.IO.StreamReader sr = null;
try{
    fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read);
    sr = new System.IO.StreamReader(fs);

    res = sr.ReadToEnd();
}
catch (System.Exception ex)
{
    HandleEx(ex);
}
finally
{
   if (sr != null)  sr.Close();
   if (fs != null)  fs.Close();
}

Or try using the using statement:

using (FileStream fileStream = File.Open(filename, FileMode.Open, FileAccess.Read))
{
    ...
}


Try using:

using (FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
    using(StreamReader sr = new System.IO.StreamReader(fs))
    {
        res = sr.ReadToEnd();
    }
}


You need to use the four-argument form of FileStream and include the access mask FileShare.Read:

var fs = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);

This way the file is opened in a way that allows for multiple concurrent readers. Additionally, the code that is writing the file also needs to open it with FileShare.Read.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜