Search code examples
c#powershelllocked-files

Clear content of a locked logfile in C#


There are many explanations out there how to empty a log file.

Like:

File.WriteAllText(activeTab.FileName, string.Empty);

But this example and other examples I found all have the same problem. It do not work if the logfile is currently locked by another process.

In ruby there is a task I can use rake log:clear which do not remove, just empty the log files.

I found also that I can this with Powershell using clc <filename>. The sources are available here now:

https://github.com/PowerShell/PowerShell/blob/c1faf1e6e10fc1ce45e84ef6f49ae7136c67a111/src/Microsoft.PowerShell.Commands.Management/commands/management/ClearContentCommand.cs

But honestly I do not understand how this code works, also it inherits from other classes.

Is there a C# implementation available that I can use in any common program/class?


Solution

  • Turns out that the file can be cleared in my case using this snippet:

      var stream = new FileStream(FileName, FileMode.Truncate, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete);
      stream.Close();