FileStream 未关闭文件

发布于 2024-12-14 21:31:14 字数 380 浏览 6 评论 0原文

我有以下代码:

using (MemoryStream str = new MemoryStream())
      {
             Program.api.GetDocument(result, str);
             using (FileStream fileStream = File.Create(filePath))
             {
                    str.WriteTo(fileStream);
             }
      }

每当写入文件时,它总是会被锁定 - 尝试删除它或修改它会导致 Windows 告诉我该文件正在使用,即使在关闭我的应用程序之后也是如此。我错过了什么吗?

I have the following code:

using (MemoryStream str = new MemoryStream())
      {
             Program.api.GetDocument(result, str);
             using (FileStream fileStream = File.Create(filePath))
             {
                    str.WriteTo(fileStream);
             }
      }

Whenever a file is written, it is always locked afterwards - attempting to delete it or modify it causes Windows to tell me the file is in use, even after closing my application. Am I missing something?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

薄荷港 2024-12-21 21:31:14

您的问题很可能是由 Windows 搜索索引引起的,该索引是 的一部分Windows 搜索。如果您尝试在修改文件后立即(或很快)访问该文件,则可能会遇到您所看到的问题。解决此问题的最佳方法是将重试逻辑添加到您正在执行的文件操作中,该逻辑会等待一小段时间并重新尝试文件操作。

如果您想确认问题是由 Windows 文件搜索索引引起的,您可以 针对文件类型和/或您写入文件的位置禁用它,看看是否可以解决问题。

Your problem is most likely caused by Windows Search Indexing which is a part of Windows Search. If you attempt to access the file immediately (or very shortly) after modifying it, you may run into the sort of issues you are seeing. The best way around this is to add retry logic to the file operation you are performing, which waits some small period of times and re-attempts the file op.

If you would like to confirm that the problem is cause by Windows File Search Indexing, you can disable it for the file type and/or location where you are writing your file to see if that makes the problem go away.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文