使用下面這段程式碼讀取檔案時出現錯誤:
錯誤訊息如下:
原因是此檔案已被其他應用程式開啟,所以我們無法存取該檔案。
不過假設沒有要寫入,只要讀取資料的話我們可以使用「唯獨」的方式開啟檔案,並允許其他程式存取,就可以正常開啟檔案並讀取資料了!
稍微解釋一下,在第二行中的 FileMode.Open 表示開啟檔案, FileAccess.Read 為只讀取,FileShare.ReadWrite 則表示允許其他檔案進行存取。
string path = @"C:\Users\ruyut\Desktop\Doc.docx";
string text = File.ReadAllText(path);
錯誤訊息如下:
Unhandled exception. System.IO.IOException: The process cannot access the file 'C:\Users\ruyut\Desktop\Doc.docx' because it is being used by another process.
at Microsoft.Win32.SafeHandles.SafeFileHandle.CreateFile(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options)
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String fullPath, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
at System.IO.Strategies.OSFileStreamStrategy..ctor(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
at System.IO.Strategies.FileStreamHelpers.ChooseStrategyCore(String path, FileMode mode, FileAccess access, FileShare share, FileOptions options, Int64 preallocationSize)
at System.IO.Strategies.FileStreamHelpers.ChooseStrategy(FileStream fileStream, String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, Int64 preallocationSize)
at System.IO.StreamReader.ValidateArgsAndOpenPath(String path, Encoding encoding, Int32 bufferSize)
at System.IO.File.InternalReadAllText(String path, Encoding encoding)
at System.IO.File.ReadAllText(String path)
at Program.<Main>$(String[] args)
原因是此檔案已被其他應用程式開啟,所以我們無法存取該檔案。
不過假設沒有要寫入,只要讀取資料的話我們可以使用「唯獨」的方式開啟檔案,並允許其他程式存取,就可以正常開啟檔案並讀取資料了!
string path = @"C:\Users\ruyut\Desktop\Doc.docx";
using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8))
{
var text = streamReader.ReadToEnd();
Console.WriteLine(text);
}
}
稍微解釋一下,在第二行中的 FileMode.Open 表示開啟檔案, FileAccess.Read 為只讀取,FileShare.ReadWrite 則表示允許其他檔案進行存取。
感謝教學~
回覆刪除