Search code examples
c#filestreamtemporary-files

creating a temp file using(FileStream) results in "The process cannot access the file because it is being used"


I'm reading a file from a SQL server and writing it to disk temporarily so that another program can access it. Pretty easy with Path.GetTempFileName().

My problem is that I need these temp files deleted once the process has been completed. I'm doing this with the FileStream class, such as:

using (FileStream fs = new FileStream(filename, FileMode.Create, FileAccess.Write,    FileShare.None, 8, FileOptions.DeleteOnClose))
{  
  //code here ultimately accessing the temp file
}

With the fileOptions set, the file is deleted once the using is finished and FileStream is disposed. The file is definitely creating and deleting on cue, but any process accessing the file responds with "The process cannot access the file because it is being used..."

Understandable if my FileStream still has access to the file (I've tried modifying the FileShare without success; this other process is not a filestream.)

I'm hoping to avoid using delete methods (which will require more error trapping). Is there a simple way to (utilizing the FileStream) create my temp file and remove it once the other process is complete?


Solution

  • I don't see a possibility here with the using statement, but you can use the Process.WaitForExit() method to wait for the other process to end, after which you can safely delete the file.