简体   繁体   English

如何清除文本文件内容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();
    }
}

but i get this error但我收到这个错误

The process cannot access the file  because it is being used by another process.

but this not open in anywhere ,但这在任何地方都没有打开,

please help me thank's请帮助我谢谢

That's because you're creating a StreamWriter , then using File.WriteAllText .那是因为您正在创建StreamWriter ,然后使用File.WriteAllText Your File is already being accessed with the StreamWriter .您的 File 已被StreamWriter访问。

File.WriteAllText does just that, writes the entire string you pass to it to a file. File.WriteAllText就是这样做的,将您传递给它的整个字符串写入文件。 StreamWriter is unnecessary if you're going to use File.WriterAllText .如果您要使用File.WriterAllText则不需要StreamWriter

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);
}

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 ):如果你想使用StreamWriter (顺便说一下, File.WriteAllText使用它,它只是隐藏它), File.WriteAllText加到文件,你可以这样做(来自这个答案):

using(StreamWriter sw = File.AppendText(path))
{
    tw.WriteLine(text);
}

You can use StreamWriter for creating a file for write and use Truncate to write with clearing previous content.您可以使用StreamWriter创建用于写入的文件,并使用Truncate进行写入并清除以前的内容。

StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();

This use FileMode.Truncate这使用FileMode.Truncate

Truncate Specifies that an existing file it to be opened and then truncated so that its size is zero bytes. Truncate指定要打开的现有文件,然后将其截断,使其大小为零字节。

Assuming that your file already exists and you want to clear its contents before populating it or whatever, I found the best way to do this with StreamWriter is..假设您的文件已经存在并且您想在填充它之前清除其内容或其他任何内容,我发现使用 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);
        }
      }

You only need to specify false in the second parameter of the constructor for StreamWriter ( route, false )你只需要在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();
}

The problem is with you locking the file by initializing StreamWriter onto filePath and then trying to call File.WriteAllText which also internally attempts to lock the file and eventually end up with an exception being thrown.问题在于您通过将StreamWriter初始化到filePath然后尝试调用File.WriteAllText来锁定文件,后者也在内部尝试锁定文件并最终以抛出异常告终。

Also from what it looks you are trying to clear the file's content and then write something in.同样从它的外观来看,您正在尝试清除文件的内容,然后再写入一些内容。
Consider the following:考虑以下:

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);

}

Why not use FileStream with FileMode.Create ?为什么不将FileStreamFileMode.Create一起使用?

using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
    //Do something...
}

Look at the MSDN of FileMode Enum看MSDN的FileMode Enum

Create创建
Specifies that the operating system should create a new file .指定操作系统应该创建一个新文件 If the file already exists, it will be overwritten .如果文件已经存在,它将被覆盖 This requires Write permission.这需要写入权限。 FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; FileMode.Create 相当于请求如果文件不存在,则使用CreateNew; otherwise, use Truncate.否则,使用截断。 If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.如果文件已存在但为隐藏文件,则抛出 UnauthorizedAccessException 异常。

Overwritten will cover/remove/clean/delete all existed file data.覆盖将覆盖/删除/清理/删除所有存在的文件数据。
if you would like to use StreamWriter , use new StreamWriter(fs) .如果您想使用StreamWriter ,请使用new StreamWriter(fs)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM