Harry
Harry

Reputation: 1705

Empty File Content Which Used by Another Process

I have a log file of my application, I do some manipulation by sided application on the log file. At the end of the manipulation, I want to delete the file - which is not possible becuase file is used, so I just want to empty it - delete the contents.

I tried:

 using (FileStream stream = File.Open(query.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
        {
            using (StreamWriter writer = new StreamWriter(stream, true))
            {
                writer.Write("");
                reader.Close();
            }
        }

and:

using (FileStream stream = File.Open(query.FileName, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))
    {
        stream.SetLength(0);
        stream.Close();
    }

and:

System.IO.File.WriteAllText(@"path", string.Empty);

Notihg works.

How to overrride file content?

Upvotes: 0

Views: 316

Answers (2)

Hans Passant
Hans Passant

Reputation: 942328

Not at all. It will crash, because file is being used by another process

Well, it probably isn't another process, it probably is yours. You'll have to do this after closing the log file. But there's a more general fix for that. Go back to the code that creates the log file and add the FileShare.Delete option.

This option allows deleting files that are in use. You can now simply use File.Delete() in your code, even if the log file is still opened. This will put the file in a "delete pending" state, anybody that tries to open it will be slapped with an access denied error. The file on the disk will automatically disappear when the last handle to the file is closed.

Yet another useful option is FileOptions.DeleteOnClose. Now it is completely automatic, the file is automatically deleted without you having to do anything at all. I can't tell which one is best in your case, you probably want to avoid deleting the log file when your program crashed so FileShare.Delete is best.

Upvotes: 2

Nirmal
Nirmal

Reputation: 1245

You can use the below code too

System.IO.File.WriteAllText(@"Path of your file",string.Empty);

Upvotes: 0

Related Questions