【问题标题】:How to append text to all existing .txt documents in C#?如何在 C# 中将文本附加到所有现有的 .txt 文档?
【发布时间】:2017-03-03 22:18:05
【问题描述】:

所以我有这个代码:

class Program
    {

        static void Main(string[] args)
        {
            // Set a variable to the My Documents path.
            string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            var dir = new DirectoryInfo(mydocpath + @"\sample\");
            string msg = "Created by: Johny";

            foreach (var file in dir.EnumerateFiles("*.txt")) 
            {
                file.AppendText(msg); //getting error here
            }
        }
    }

我想为示例文件夹中的所有文本文件添加页脚,但由于 AppendText 不接受字符串参数,因此出现错误。我只是想知道我该怎么做?

【问题讨论】:

    标签: c# system.io.file appendtext


    【解决方案1】:

    我认为您想使用 AppendText 中的流写入器:

            static void Main(string[] args)
            {
                // Set a variable to the My Documents path.
                string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    
                var dir = new DirectoryInfo(mydocpath + @"\sample\");
                string msg = "Created by: Johny";
    
                foreach (var file in dir.EnumerateFiles("*.txt"))
                {
                    var streamWriter = file.AppendText(); 
                    streamWriter.Write(msg);
                    streamWriter.Close();
                }
            }
    

    【讨论】:

      【解决方案2】:

      FileInfo.AppendText() 创建一个StreamWriter,它本身不附加文本。你想这样做:

      using (var sw = file.AppendText()) {
          sw.Write(msg);
      }
      

      【讨论】:

        【解决方案3】:

        AppendTextStreamWriter的扩展方法,见documentation

        所以你应该改写这些代码:

        foreach (var file in dir.EnumerateFiles("*.txt")) 
        {
            using (StreamWriter sw = File.AppendText(file.FullName))
            {
                sw.WriteLine(msg);
            }
        }   
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-07-16
          • 2010-10-27
          • 1970-01-01
          • 2014-02-22
          • 1970-01-01
          • 1970-01-01
          • 2011-12-19
          • 2016-10-23
          相关资源
          最近更新 更多