问题
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