[c#] How can I clear the content of a file?

I need to clear the contents of a particular file every time the applications starts. How do I do it?

This question is related to c# .net file

The answer is


Use FileMode.Truncate everytime you create the file. Also place the File.Create inside a try catch.


This is what I did to clear the contents of the file without creating a new file as I didn't want the file to display new time of creation even when the application just updated its contents.

FileStream fileStream = File.Open(<path>, FileMode.Open);

/* 
 * Set the length of filestream to 0 and flush it to the physical file.
 *
 * Flushing the stream is important because this ensures that
 * the changes to the stream trickle down to the physical file.
 * 
 */
fileStream.SetLength(0);
fileStream.Close(); // This flushes the content, too.

The easiest way is:

File.WriteAllText(path, string.Empty)

However, I recommend you use FileStream because the first solution can throw UnauthorizedAccessException

using(FileStream fs = File.Open(path,FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
     lock(fs)
     {
          fs.SetLength(0);
     }
}

Try using something like

File.Create

Creates or overwrites a file in the specified path.


The simplest way to do this is perhaps deleting the file via your application and creating a new one with the same name... in even simpler way just make your application overwrite it with a new file.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to file

Gradle - Move a folder from ABC to XYZ Difference between opening a file in binary vs text Angular: How to download a file from HttpClient? Python error message io.UnsupportedOperation: not readable java.io.FileNotFoundException: class path resource cannot be opened because it does not exist Writing JSON object to a JSON file with fs.writeFileSync How to read/write files in .Net Core? How to write to a CSV line by line? Writing a dictionary to a text file? What are the pros and cons of parquet format compared to other formats?