简体   繁体   中英

FileStream not closing file

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM