web-dev-qa-db-ja.com

ファイルの内容をクリアするにはどうすればよいですか?

アプリケーションを起動するたびに特定のファイルの内容をクリアする必要があります。どうすればいいのですか?

71
olive

File.WriteAllText メソッドを使用できます。

System.IO.File.WriteAllText(@"Path/foo.bar",string.Empty);
115

これは私がやったことです新しいファイルを作成せずにファイルの内容を消去しますアプリケーションがその内容を更新したばかりでもファイルに新しい作成時刻を表示させたくないので。

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.
74
Abhay Jain

つかいます FileMode.Truncateファイルを作成するたびに。また、File.Createtrycatch内。

10
sajoshi

これを行う最も簡単な方法は、おそらくアプリケーションを介してファイルを削除し、同じ名前の新しいファイルを作成することです。もっと簡単な方法では、アプリケーションを新しいファイルで上書きするだけです。

2
Kartikya

のようなものを使用してみてください

File.Create

指定されたパスにファイルを作成または上書きします。

1
Adriaan Stander

最も簡単な方法は次のとおりです。

File.WriteAllText(path, string.Empty)

ただし、最初のソリューションではFileStreamをスローできるため、UnauthorizedAccessExceptionを使用することをお勧めします。

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