在FileStream上关闭/处理

时间:2013-12-31 11:47:34

标签: c# filestream idisposable

我在支持复制文件的产品中有一些代码:

using(System.IO.FileStream sourceFS = new System.IO.FileStream(sourcePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
            {
                using(System.IO.FileStream targetFS = new System.IO.FileStream(targetPath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read))
                {
                    while((read = sourceFS.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        targetFS.Write(buffer, 0, read);
                    }

                    targetFS.Flush();
                    targetFS.Close();
                }

                sourceFS.Close();
            }

不幸的是,用户报告了一个异常,通知我们目标文件正由另一个进程使用。我问过是否有人打开文件(这是一个Excel文件) - 显然不是......

所以,我把思考上限......我们是否有可能将文件锁定在目标文件中?我可以看到targetFS不被关闭的唯一方法是:

  1. 要在内部使用块中抛出的异常,
  2. Dispose方法不实际关闭流。
  3. 对我来说这听起来不太可能,但好奇的是我使用JetBrains中的dotPeek来反汇编FileStream类上的Dispose方法 - 这似乎并没有真正做到这一点 - 我猜它提供了“近距离”行为通过处理手柄......

    从本质上讲 - 问题是这个 - 有人能发现这可能会导致文件被锁定吗?

1 个答案:

答案 0 :(得分:2)

看看其他地方。这段代码很好。不知道还有什么可说的。 using仅用于此用例 - 故障安全处理。

使用Process Explorer调查哪个进程持有相关文件的句柄。

相关问题