如何清除文本文件内容c# [英] how to clear text file content c#
问题描述
我想用这种方法清除文本文件
i want clear text file contet with this method
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.
但这不是在任何地方打开,
but this not open in anywhere ,
请帮帮我谢谢
推荐答案
那是因为您正在创建一个 StreamWriter
,然后使用 File.WriteAllText
.您的文件已被 StreamWriter
访问.
That's because you're creating a StreamWriter
, then using File.WriteAllText
. Your File is already being accessed with the StreamWriter
.
File.WriteAllText
就是这样做的,将传递给它的整个字符串写入文件.如果您要使用 File.WriterAllText
,则不需要 StreamWriter
.
File.WriteAllText
does just that, writes the entire string you pass to it to a file. StreamWriter
is unnecessary if you're going to use File.WriterAllText
.
如果您不关心覆盖现有文件,您可以这样做:
If you don't care about overwriting an existing file, you can do this:
private void writeTextFile(string filePath, string text)
{
File.WriteAllText(filePath, text);
}
如果你想使用 StreamWriter
(顺便说一下,File.WriteAllText
使用,它只是隐藏它),并附加到文件,你可以这样做这个(来自这个答案):
If you want to use StreamWriter
(which, by the way, File.WriteAllText
uses, it just hides it), and append to the file, you can do this (from this answer):
using(StreamWriter sw = File.AppendText(path))
{
tw.WriteLine(text);
}
这篇关于如何清除文本文件内容c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!