kosnkov
kosnkov

Reputation: 5941

Move or delete when file open

Is it possible to move/delete a file inside using a statement like this:

using (
    var fileStream = new FileStream(
        @"someShare\someFile.txt",
        FileMode.Open,
        FileAccess.Read,
        FileShare.None,
        512,
        FileOptions.None))
{
    // Here how to remove that file and then release stream? 
}

What I want to achieve is to copy the file to the archive after my process finishes processing, but before releasing the stream.

If I move the file after using statement it is possible that some other instance of my code will lock the file.

FileOptions.DeleteOnClose is not an option because I do not want to remove the file if there will be any exception inside using statement

Upvotes: 1

Views: 1495

Answers (3)

Jeroen Mostert
Jeroen Mostert

Reputation: 28789

FileOptions.DeleteOnClose "indicates that a file is automatically deleted when it is no longer in use" So you can do:

using (
    var fileStream = new FileStream(
        @"someShare\someFile.txt",
        FileMode.Open,
        FileAccess.Read,
        FileShare.None,
        512,
        FileOptions.DeleteOnClose
    )
) {
    // do something nice with the stream
}

Note that if other processes (or even your own) have already opened the file elsewhere, it will remain open until the last handle to it is closed. It will not necessarily be deleted immediately after you're done with it (but with FileShare.None, you can be reasonably sure you are the only one using it, otherwise the stream would not have opened).

Upvotes: 4

rokkerboci
rokkerboci

Reputation: 1167

You can use a using block, but you have to specifiy you want to delete it.

using (FileStream stream = new FileStream(path, FileMode.Truncate, FileAccess.Write, FileShare.Delete, 4096, true))
{
    stream.Flush();
    File.Delete(path);
}

Upvotes: 2

JamesFaix
JamesFaix

Reputation: 8655

You don't need a using block. Just use System.IO.File.Delete.

https://msdn.microsoft.com/en-us/library/system.io.file.delete(v=vs.110).aspx

Upvotes: -3

Related Questions