Getting around file access protection in Windows to view an active logfile read-only

佐手、 提交于 2019-12-14 03:59:44

问题


A customer asked for quick and dirty log viewer for an ASP.NET app, for which I'm using log4net, and I thought somehow we could simply add a controller to read the tail of the active file and spit it back.

If I use the standard .NET API (File.OpenText, etc.) I get access violation (file open by another process), which is what I expect, but I know it is possible to read the file because Ultraedit opens it for viewing read-only. Can I do the same from the .NET API?

using(StreamReader infile =
         System.IO.File.OpenText(Request.PhysicalApplicationPath + @"\log\my.log"))
{
}

回答1:


Specify That you allow read/write sharing on the file, and put a StreamReader on your stream to get the same behaviour as File.OpenText.

using( Stream stream = File.Open(@"x:\path\file.log", 
        FileMode.Open, FileAccess.Read, FileShare.ReadWrite) )
{
    using(StreamReader sr = new StreamReader(stream))
    {
        //read content
    }
}

And since you can open the file with UltraEdit, I assume log4net is not putting an exclusive lock on the file.




回答2:


Did you try:

        using (FileStream fs = File.OpenRead("C:\\1.txt"))
        {
            //read here
        }


来源:https://stackoverflow.com/questions/4318111/getting-around-file-access-protection-in-windows-to-view-an-active-logfile-read

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!