0

So I have this code:

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

And I want to add a footer to all the text file in the sample folder, but I'm getting an error because the AppendText is not accepting a string argument. I was just wondering how do I do this?

Antonio Mercado
  • 55
  • 1
  • 10

3 Answers3

1

FileInfo.AppendText() creates a StreamWriter, it doesn't append text per se. You want to do this:

using (var sw = file.AppendText()) {
    sw.Write(msg);
}
Tim
  • 5,940
  • 1
  • 12
  • 18
1

You want to use the streamwriter from AppendText I think:

        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();
            }
        }
Chris Nevill
  • 5,922
  • 11
  • 44
  • 79
0

AppendText is the extension method for the StreamWriter, see the documentation

So you should write these code instead:

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