Borrar el contenido del archivo de texto usando C#


¿Cómo puedo borrar el contenido de un archivo de texto usando C# ?

Author: Morano88, 2010-04-23

5 answers

File.WriteAllText(path, String.Empty);

Alternativamente,

File.Create(path).Close();
 147
Author: SLaks,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-23 00:33:59

Simplemente abra el archivo con el modo de archivo .Trunca la bandera, luego ciérrala:

using (var fs = new FileStream(@"C:\path\to\file", FileMode.Truncate))
{
}
 17
Author: Dean Harding,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-23 00:34:56
 using (FileStream fs = File.Create(path))
 {

 }

Creará o sobrescribirá un archivo.

 5
Author: womp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-04-23 00:35:24

Otra versión corta:

System.IO.File.WriteAllBytes(path, new byte[0]);
 2
Author: Ivan Kochurkin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-02 21:02:04

Puedes usar siempre stream writer.It borrará los datos antiguos y añadirá uno nuevo cada vez.

using (StreamWriter sw = new StreamWriter(filePath))
{                            
    getNumberOfControls(frm1,sw);
}
 -2
Author: Harry007,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-14 11:47:58