开发者

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

开发者 https://www.devze.com 2023-01-30 02:14 出处:网络
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().

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?


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.


If you running on the Windows OS, DeleteOnClose is actually backed up by the FILE_FLAG_DELETE_ON_CLOSE flags passed to the CreateFile Function

Documentation says: "The file is to be deleted immediately after all of its handles are closed, which includes the specified handle and any other open or duplicated handles."

So you need to call DuplicateHandle (doc here) on FileStream's Handle or SafeFileHandle property. You should be able to do this in the using. Here is one possibility of DuplicateHandle declaration in C#:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool DuplicateHandle(
    IntPtr hSourceProcess,
    SafeFileHandle hSourceHandle,
    IntPtr hTargetProcessHandle,
    out IntPtr hTargetHandle,
    uint dwDesiredAccess,
    bool fInheritHandle,
    uint dwOptions);

I have not tested this, but It has good chances to work :-)


Close th fileStream using Close() method of the stream before the closing of using clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号