【问题标题】:Write string to text file and ensure it always overwrites the existing content.将字符串写入文本文件并确保它始终覆盖现有内容。
【发布时间】:2010-11-16 14:04:39
【问题描述】:

我有一个带有 C# 程序的字符串,我想将其写入文件并始终覆盖现有内容。如果文件不存在,程序应该创建一个新文件而不是抛出异常。

【问题讨论】:

    标签: c# file text


    【解决方案1】:

    使用文件模式枚举来更改File.Open 行为。这适用于二进制内容和文本。

    由于FileMode.OpenFileMode.OpenOrCreate 将现有内容加载到文件流中,如果要完全替换文件,则需要先清除现有内容(如果有),然后再写入流。 FileMode.Truncate 自动执行此步骤

    // OriginalFile:
    oooooooooooooooooooooooooooooo
    
    // NewFile:
    ----------------
    
    // Write to file stream with FileMode.Open:
    ----------------oooooooooooooo
    
    var exists = File.Exists(path);
    var fileMode = exists
        ? FileMode.Truncate   // overwrites all of the content of an existing file
        : FileMode.CreateNew  // creates a new file
    
    using (var destinationStream = File.Open(path, fileMode)
    {
        await newContentStream.CopyToAsync(destinationStream);
    }
    

    FileMode Enum

    【讨论】:

      【解决方案2】:
      System.IO.File.WriteAllText (@"D:\path.txt", contents);
      
      • 如果文件存在,则会覆盖它。
      • 如果文件不存在,则会创建它。
      • 请确保您有适当的权限在该位置写入,否则您将获得例外。

      【讨论】:

        【解决方案3】:

        通常,FileMode.Create 是您要查找的内容。

        【讨论】:

        • 他要求覆盖现有文件
        【解决方案4】:

        如果您的代码不需要首先截断文件,您可以使用 FileMode.OpenOrCreate 打开文件流,如果文件不存在则创建文件,如果文件存在则打开文件。您可以使用流指向前面并开始覆盖现有文件吗?

        我假设您在这里使用流,还有其他方法可以写入文件。

        【讨论】:

          【解决方案5】:

          使用File.WriteAllText 方法。如果文件不存在则创建该文件,如果存在则覆盖它。

          【讨论】:

          • 啊。如此简单和有用。
          猜你喜欢
          • 2017-07-13
          • 2012-01-03
          • 2011-05-08
          • 1970-01-01
          • 1970-01-01
          • 2013-11-02
          • 2018-01-18
          • 1970-01-01
          相关资源
          最近更新 更多