【问题标题】:how to clear text file content c#如何清除文本文件内容c#
【发布时间】:2014-03-14 11:21:46
【问题描述】:

我想用这个方法来明文文件内容

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.

但这不是在任何地方打开的,

请帮帮我 谢谢

【问题讨论】:

    标签: c# streamwriter


    【解决方案1】:

    为什么不将FileStreamFileMode.Create 一起使用?

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

    FileMode Enum的MSDN

    创建
    指定操作系统应该创建一个新文件如果文件已经存在,则会被覆盖。这需要写权限。 FileMode.Create相当于请求如果文件不存在就使用CreateNew;否则,使用截断。如果文件已经存在但为隐藏文件,则抛出 UnauthorizedAccessException 异常。

    覆盖将覆盖/移除/清理/删除所有已存在的文件数据。
    如果您想使用StreamWriter,请使用new StreamWriter(fs)

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:
        // 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】:

          假设您的文件已经存在,并且您想在填充之前清除其内容或其他任何内容,我发现使用 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!")
          

          【讨论】:

            【解决方案5】:

            您可以使用StreamWriter 来创建用于写入的文件,并使用Truncate 来写入并清除以前的内容。

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

            这个用FileMode.Truncate

            Truncate 指定将现有文件打开然后截断,使其大小为零字节。

            【讨论】:

              【解决方案6】:

              问题在于您通过将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);
              
              }
              

              【讨论】:

              • 我认为第二个参数不是追加,而是编码。
              • 有两个构造函数,一个以编码作为第二个参数,另一个以布尔值作为第二个参数。 msdn.microsoft.com/en-us/library/…
              【解决方案7】:

              那是因为您要创建一个StreamWriter,然后使用File.WriteAllText。您的文件已被StreamWriter 访问。

              File.WriteAllText 就是这样做的,将传递给它的整个字符串写入文件。如果您要使用File.WriterAllText,则不需要StreamWriter

              如果您不关心覆盖现有文件,您可以这样做:

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

              【讨论】:

              • 或者此时完全删除该方法并让调用者直接调用File.WriteAllText,因为该方法什么也没做。
              • @Servy 是的!我只是使用现有的模板。
              猜你喜欢
              • 1970-01-01
              • 2011-02-11
              • 1970-01-01
              • 2014-09-02
              • 1970-01-01
              • 2011-06-16
              • 1970-01-01
              • 2010-11-07
              • 1970-01-01
              相关资源
              最近更新 更多