FileStream保存文件然后立即在.NET中解锁?

我有这个代码保存pdf文件。

FileStream fs = new FileStream(SaveLocation, FileMode.Create); fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length); fs.Flush(); fs.Close(); 

它工作正常。 但是,有时它不会立即释放锁定,并导致文件锁定exception,并且在此次运行后运行函数。

fs.Close() 之后是否有理想的方法来释放文件锁

这是理想的:

 using (var fs = new FileStream(SaveLocation, FileMode.Create)) { fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length); } 

这大致相当于:

 FileStream fs = null; try { fs = new FileStream(SaveLocation, FileMode.Create); fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length); } finally { if (fs != null) { ((IDisposable)fs).Dispose(); } } 

使用更具可读性。


更新:

@aron,现在我在想

 File.WriteAllBytes(SaveLocation, result.DocumentBytes); 

看起来比理想的更漂亮:-)

我们在生产中看到了同样的问题,并使用包含它的using()语句。

这里的罪魁祸首之一是反病毒软件,它可以在文件关闭后潜入,在发布之前抓住它以检查它是否包含病毒。

但即使所有防病毒软件都处于混合状态,在存储在网络共享上的文件的高负载系统中,我们偶尔也会看到这个问题。 A,咳嗽,短暂的Thread.Sleep(),咳嗽,关闭后似乎治好了。 如果有人有更好的解决方案,我很乐意听到它!

我无法想象为什么在文件关闭后会保持锁定。 但是您应该考虑将其包装在using语句中,以确保即使引发exception也会关闭该文件

 using (FileStream fs = new FileStream(SaveLocation, FileMode.Create)) { fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length); } 

如果在这个之后运行的函数是同一个应用程序的一部分,那么更好的方法可能是在整个过程开始时打开文件进行读/写,然后将文件传递给每个函数而不关闭它直到结束了。 然后,应用程序不必阻止等待IO操作完成。

当使用.Flush()时,这对我有用。我必须在using语句中添加一个close。

  using (var imageFile = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite,FileShare.ReadWrite)) { imageFile.Write(bytes, 0, bytes.Length); imageFile.Flush(); imageFile.Close(); }