FileStream not closing file

霸气de小男生 提交于 2019-12-21 04:21:28

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/8081243/filestream-not-closing-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!