Clearing content of text file using C#
136,276
Solution 1
File.WriteAllText(path, String.Empty);
Alternatively,
File.Create(path).Close();
Solution 2
Just open the file with the FileMode.Truncate flag, then close it:
using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}
Solution 3
using (FileStream fs = File.Create(path))
{
}
Will create or overwrite a file.
Solution 4
You can clear contents of a file just like writing contents in the file but replacing the texts with ""
File.WriteAllText(@"FilePath", "");
Solution 5
Another short version:
System.IO.File.WriteAllBytes(path, new byte[0]);
Author by
Morano88
Updated on July 05, 2022Comments
-
Morano88 almost 2 years
How can I clear the content of a text file using C# ?
-
Dean Harding about 14 yearsWow, even shorter than mine! +1
-
SLaks about 14 yearsSince there's no code in the block, the
using
statement offers no advantage over.Close()
. -
nuiun about 14 yearsI'm assuming he'd be doing something with the file.
-
Zer0 over 8 yearswhat do you mean "shorter" than yours?
-
SLaks over 8 years@F4z: Far fewer characters.