我希望使用此方法明确文本文件内容
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.
但这不会在任何地方开放,
请帮帮我 感谢
答案 0 :(得分:13)
那是因为您正在创建StreamWriter
,然后使用File.WriteAllText
。您的文件已被StreamWriter
访问。
File.WriteAllText
就是这样,将传递给它的整个字符串写入文件。如果您要使用StreamWriter
,则无需File.WriterAllText
。
如果您不在乎覆盖现有文件,可以执行以下操作:
private void writeTextFile(string filePath, string text)
{
File.WriteAllText(filePath, text);
}
如果您想使用StreamWriter
(顺便说一下,File.WriteAllText
使用它,它只是隐藏它),并附加到该文件,您可以执行此操作(来自this answer ):
using(StreamWriter sw = File.AppendText(path))
{
tw.WriteLine(text);
}
答案 1 :(得分:1)
您可以使用StreamWriter
创建用于写入的文件,并使用Truncate
进行写入以清除之前的内容。
StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();
这次使用FileMode.Truncate
Truncate
指定要打开然后截断的现有文件,使其大小为零字节。
答案 2 :(得分:1)
假设您的文件已经存在并且您希望在填充它之前清除其内容或其他内容,我发现使用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!")
答案 3 :(得分:1)
// 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);
}
}
答案 4 :(得分:1)
您只需要在 StreamWriter (路由, false )
的构造函数的第二个参数中指定falseString 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();
}
答案 5 :(得分:0)
问题在于您通过将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);
}
答案 6 :(得分:0)
为什么不将FileStream
与FileMode.Create
一起使用?
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
//Do something...
}
查看FileMode Enum的MSDN
创建
指定操作系统应创建新文件。 如果文件已经存在,它将被覆盖。这需要写权限。 FileMode.Create等效于请求如果文件不存在,则使用CreateNew;否则,使用截断。如果该文件已经存在但为隐藏文件,则会引发UnauthorizedAccessException异常。
覆盖将覆盖/删除/清除/删除所有现有文件数据。
如果您想使用StreamWriter
,请使用new StreamWriter(fs)
。