如何在 C# 中将文本附加到所有现有的 .txt 文档?

How to append text to all existing .txt documents in C#?

所以我有这个代码:

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 不接受字符串参数。我只是想知道我该怎么做?

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

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

你想使用 AppendText 中的 streamwriter 我认为:

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

AppendTextStreamWriter的扩展方法,见documentation

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

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