9

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?

Chris
  • 7,415
  • 21
  • 98
  • 190
  • 5
    This usage seems fine. Are you sure there isn't more code dealing with `filePath`? – Oded Nov 10 '11 at 14:49
  • I think you may be missing a `str.Position = 0;` but that would not lock the fileStream – H H Nov 10 '11 at 15:15
  • 1
    I agree that the specified code cannot cause a lock on the file past the final } of the code. There must be something else causing it. Even an exception inside the using statement would cancel the lock, afaik. – pyrocumulus Nov 10 '11 at 15:18
  • 4
    "even after closing my application" means it's not your application's fault. All open handles of your process get closed when you terminate it. So it must be some other program keeping it open. – CodesInChaos Nov 10 '11 at 15:42

1 Answers1

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.

Michael Goldshteyn
  • 71,784
  • 24
  • 131
  • 181
  • 1
    Do you have any documentation or msdn examples to support the indexer locking argument? I'm suprised that the indexer isn't trolling the filesystem with open permissions of FileShare.ReadWrite – Ritch Melton Nov 10 '11 at 15:42
  • 1
    Sounds plausible at least. And depending on the location it might be an Virusscanner too. – H H Nov 10 '11 at 22:24
  • Yes, generally plausible and definitely so when a virus scanner is added to the mix. Like @RitchMelton, I do find it difficult to believe that the file system indexer is preventing access. That would be quite counter productive. – IAbstract Nov 13 '11 at 03:46