我有 2 个这样的文件流:
using (var fs = new FileStream(source, FileMode.Open, FileAccess.Write, FileShare.Read)){
//some code here
var checksum = getChecksum(source);
}
public long getChecksum(string source){
using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.Read)){
//Error: The process cannot access the file 'C:\Temp\archive.dat' because it is being used by another process.
}
}
为什么会出现这个错误?我已经将 FileAccess 设置为 Read / ReadWrite / ... 但没有任何效果。而且我无法将Stream传递给
getChecksum()
函数,因为我在其他地方使用了该函数。
上面的流不应该允许阅读吗?
Create 2 FileStream on the same file on the same process我在这个线程中找不到我的awnser。
您正在尝试打开第二个 FileStream,而第一个文件流仍处于打开状态,因为 using 块仍在范围内。 docs 说使用 FileShare.Read 时可能需要额外的权限。
在您链接的另一个线程中,有人提到可能需要将第二个流上的 FileShare 模式设置为 FileShare.ReadWrite,以便第一个仍然可以访问。这可能是最可能的原因,因为第二个试图获得除读取之外的独占访问权限,但已经打开了一个写入流。
您也可以尝试在第一个 FileStream 上调用
Flush()
以强制在调用 getCheckSum()
之前写入数据。
using (var fs = new FileStream(source, FileMode.Open, FileAccess.Write, FileShare.Read)){
//some code here
//Force the buffered data to be written
fs.Flush()
var checksum = getChecksum(source);
}
public long getChecksum(string source){
using (var fs = new FileStream(source, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){ //FileShare.ReadWrite so first FileStream can still access
}
}