如何清除文本文件内容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
。 您的文件已被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!")
问题在于您通过将StreamWriter
初始化为filePath
然后尝试调用File.WriteAllText
来锁定文件,该文件也在内部尝试锁定文件并最终导致抛出exception。
从它看起来你也试图清除文件的内容,然后写一些东西。
考虑以下:
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); }
// 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); } }