Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 603
Chris Avatar asked Nov 10 '11 14:11

Chris


1 Answers

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.

like image 92
Michael Goldshteyn Avatar answered Sep 23 '22 09:09

Michael Goldshteyn