【发布时间】:2016-05-07 04:13:24
【问题描述】:
我正在打开一个 FileStream 并使用以下两个代码 sn-ps 向其写入行:
public static System.IO.FileStream OpenFileStream(string FullFilename) {
return new System.IO.FileStream(FullFilename, System.IO.FileMode.OpenOrCreate,
System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read);
}
public static void WriteLine(System.IO.FileStream fileStream, string str) {
fileStream.Seek(0, System.IO.SeekOrigin.End);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str + "\r\n");
fileStream.Write(bytes, 0, bytes.Length);
fileStream.Flush();
}
被访问的文件,即OpenFileStream中的FullFilename参数,是一个CSV文件。打开文件后,要求能够看到到目前为止写入 CSV 文件的内容。
我一直在使用 Microsoft Excel,当 Excel 打开文件时,它会注意到该文件正在使用中并给我一个对话框,告诉我我只能获得只读访问权限。尽管如此,即使OpenFileStream 授予其他程序的访问权限是System.IO.FileShare.Read,Excel 尝试打开文件的行为有时也会导致在获得打开的 FileStream 的程序中引发异常。
被抛出的异常是带有消息The process cannot access the file because another process has locked a portion of the file 的System.IO.IOException,它可以在访问FileStream 的WriteLine 函数中的任何位置被抛出。
如何防止其他程序(如 Excel)尝试读取文件时引发任何异常?
【问题讨论】:
-
您不能将文件流的内容复制到内存流中,以便不再访问该文件还是我误解了这个问题?
-
@AlexanderDerck 我需要能够看到到目前为止所写的内容,所以我认为存储在内存中没有帮助。
-
看来这是正确的方法。问题是当文件已经打开以供写入时 - 然后您无法打开它。
-
@i486 我不想打开 Excel 中的文字,只是阅读。但是,为“只读”打开的行为仍然会导致抛出异常。
-
@Stochasticly Excel 导致
LockFileEx(Win32) 异常。如果您以相同的方式(使用 LockFileEx)锁定文件,可能会保护它。
标签: c# .net io filestream