[英]how to clear text file content c#
我想用這種方法清除文本文件內容
private void writeTextFile(string filePath, string text)
{
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
using (StreamWriter tw = new StreamWriter(filePath))
{
File.WriteAllText(filePath,"");
tw.WriteLine(text);
tw.Close();
}
}
但我收到這個錯誤
The process cannot access the file because it is being used by another process.
但這在任何地方都沒有打開,
請幫助我謝謝
那是因為您正在創建StreamWriter
,然后使用File.WriteAllText
。 您的 File 已被StreamWriter
訪問。
File.WriteAllText
就是這樣做的,將您傳遞給它的整個字符串寫入文件。 如果您要使用File.WriterAllText
則不需要StreamWriter
。
如果您不關心覆蓋現有文件,您可以這樣做:
private void writeTextFile(string filePath, string text)
{
File.WriteAllText(filePath, text);
}
如果你想使用StreamWriter
(順便說一下, File.WriteAllText
使用它,它只是隱藏它), File.WriteAllText
加到文件,你可以這樣做(來自這個答案):
using(StreamWriter sw = File.AppendText(path))
{
tw.WriteLine(text);
}
您可以使用StreamWriter
創建用於寫入的文件,並使用Truncate
進行寫入並清除以前的內容。
StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();
這使用FileMode.Truncate
Truncate
指定要打開的現有文件,然后將其截斷,使其大小為零字節。
假設您的文件已經存在並且您想在填充它之前清除其內容或其他任何內容,我發現使用 StreamWriter 執行此操作的最佳方法是..
// this line does not create test.txt file, assuming that it already exists, it will remove the contents of test.txt
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(Path.GetFullPath(C:\test.txt), False)
// this line will now be inserted into your test.txt file
sw.Write("hey there!")
// I decided to use this solution
// this section is to clear MyFile.txt
using(StreamWriter sw = new StreamWriter(@"MyPath\MyFile.txt", false))
{
foreach(string line in listofnames)
{
sw.Write(""); // change WriteLine with Write
}
sw.Close();
}
// and this section is to copy file names to MyFile.txt
using(StreamWriter file = new StreamWriter(@"MyPath\MyFile.txt", true))
{
foreach(string line in listofnames)
{
file.WriteLine(line);
}
}
你只需要在StreamWriter ( route, false ) 構造函數的第二個參數中指定 false
String ruta = @"C:\Address\YourFile".txt";
using (StreamWriter file = new StreamWriter(ruta, false))
{
for ( int i = 0; i < settings.Length; ++i )
file.WriteLine( settings[ i ] );
file.Close();
}
問題在於您通過將StreamWriter
初始化到filePath
然后嘗試調用File.WriteAllText
來鎖定文件,后者也在內部嘗試鎖定文件並最終以拋出異常告終。
同樣從它的外觀來看,您正在嘗試清除文件的內容,然后再寫入一些內容。
考慮以下:
private void writeTextFile(string filePath, string text) {
using (StreamWriter tw = new StreamWriter(filePath, false)) //second parameter is `Append` and false means override content
tw.WriteLine(text);
}
為什么不將FileStream
與FileMode.Create
一起使用?
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
//Do something...
}
看MSDN的FileMode Enum
創建
指定操作系統應該創建一個新文件。 如果文件已經存在,它將被覆蓋。 這需要寫入權限。 FileMode.Create 相當於請求如果文件不存在,則使用CreateNew; 否則,使用截斷。 如果文件已存在但為隱藏文件,則拋出 UnauthorizedAccessException 異常。
覆蓋將覆蓋/刪除/清理/刪除所有存在的文件數據。
如果您想使用StreamWriter
,請使用new StreamWriter(fs)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.