嘗試爲桌面開發Windows應用商店應用程序時,我似乎遇到了困難。我試圖打開另一個應用程序已打開的大型(100+ MB)日誌文件,並在寫入文件時對最新事件進行實時處理。UWP - 如果其他應用程序打開文件,則無法打開文件
通過定期,非沙盒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);
看到這篇文章:http://stackoverflow.com/questions/4400517/how-can-i-read-a-file-even-when-getting-an-in-use-by-another-process -exception – Sparrow
這隻適用於非UWP應用程序,在這種情況下它不起作用。這是我嘗試的第一件事。還有,我的代碼作爲一個例子,說明什麼在我的評論中不起作用:*( –
Man,這令人沮喪..根據System.Diagnostics.Stopwatch,即使在我的系統上,ReadBufferAsync也需要100ms才能讀取一個適中的100MB日誌文件同時,對於尚未打開的文件,StorageFile的OpenAsync(...)方法需要2ms以下的時間,所以它正是我需要的。Fiddlesticks !!! –