2018年更新: 如下所示和其他来源所述,针对创意者更新或更高版本,允许只读访问已被另一个进程打开进行写入的文件。太好了!
我似乎在为桌面开发Windows Store应用程序时遇到了难题。 我试图打开另一个应用程序打开的大型(100+ MB)日志文件,并实时处理最新的事件,因为它们被写入文件。
使用常规的非沙盒化C#,这是相当简单的:
System.IO.FileStream stream = File.Open("LOGFILE PATH HERE", System.IO.FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
很遗憾,在UWP中,当我尝试打开被另一个应用程序使用的文件时,我会收到“UnauthorizedAccessException”错误。我尝试了所有我能找到的API和各种组合,但都没有成功,所以我来这里寻求一些建议。
以下是我尝试过的一些方法:
Windows.Storage.Pickers.FileOpenPicker picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.List;
//Prompt the user to open the log file:
Windows.Storage.StorageFile logFile = await picker.PickSingleFileAsync();
picker.FileTypeFilter.Add(".txt");
//This won't work in any case, because it doesn't use the handle that the user picked,
// so the UWP sandboxing blocks it:
new FileStream(logFile.Path, FileMode.OpenOrCreate, FileAccess.Read);
//EDIT: These don't work if the file is open either, I must have made a mistake earlier
await FileIO.ReadBufferAsync(logFile);
await FileIO.ReadLinesAsync(logFile);
//These work if the file is not open by another app, but fail if another app has the file open
await logFile.OpenAsync( Windows.Storage.FileAccessMode.Read);
await logFile.OpenStreamForReadAsync();
快速复现:
打开PowerShell窗口,并运行以下命令以在您的主目录中打开“test.txt”文件:
$f = [System.IO.File]::Open("test.txt", [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::Write, [System.IO.FileShare]::ReadWrite);