aro*_*ron 9 c# filestream filelock
我有这个代码保存pdf文件.
FileStream fs = new FileStream(SaveLocation, FileMode.Create);
fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
fs.Flush();
fs.Close();
Run Code Online (Sandbox Code Playgroud)
它工作正常.但是,有时它不会立即释放锁定,并导致文件锁定异常,并且在此次运行后运行函数.
有没有理想的方法在fs.Close()之后立即释放文件锁
Dar*_*rov 16
这是理想的:
using (var fs = new FileStream(SaveLocation, FileMode.Create))
{
fs.Write(result.DocumentBytes, 0, result.DocumentBytes.Length);
}
Run Code Online (Sandbox Code Playgroud)
这大致相当于:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
的使用是更具有可读性.
更新:
@aron,现在我在想
File.WriteAllBytes(SaveLocation, result.DocumentBytes);
Run Code Online (Sandbox Code Playgroud)
看起来比理想的更漂亮:-)
我们在生产中看到了同样的问题,并使用包含它的using()语句.
这里的罪魁祸首之一是反病毒软件,它可以在文件关闭后潜入,在发布之前抓住它以检查它是否包含病毒.
但是,即使所有的防病毒软件都在混合中,在存储在网络共享上的文件的高负载系统中,我们偶尔也会看到这个问题.A,咳嗽,短暂的Thread.Sleep(),咳嗽,关闭后似乎治好了.如果有人有更好的解决方案,我很乐意听到它!
| 归档时间: |
|
| 查看次数: |
15425 次 |
| 最近记录: |