Search code examples
c#system.io.fileappendtext

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


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?


Solution

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