[英]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.