将文件中的文本附加到输出,打印到文件 C#

Appending text from the file to an output,printing to file C#

我正在编写一个读取 txt 文件内容并正确检查文件名是否已被使用、是否存在等的命令方法。

我遇到的唯一问题是,在读取文件后,我无法让它写入文件内容以追加到另一个文本文件中的一行文本之后。

我已将其正确打印到控制台,但我也想将内容的文本附加到我写入文件的输出中。

有什么想法吗?我知道这是一个简单的修复,但 none 我的解决方案将附加内容...

 protected void read(string command, string param1)
        {
            //read the contents of a created file
            // check if file exists
            // if it exists send message to console that file was found
            // let user know that the file exist, but is empty
            // if file does not exist, let the user know that the file does not exist

            //checks name of the file, if it exists, then reads and displays the contents of the file in console and in audit.txt
            if (param1 == "accounts.txt" || param1 == "audit.txt" || param1 == "groups.txt" || param1 == "files.txt")
            {
                Console.WriteLine("Cannot use this filename");
                Console.Read();
                return;
            }
            //checks if file exists
            //if it doesnt exist program should terminate
            else if (!File.Exists(@"C:\Files\"))
            {
                Console.WriteLine("Filename doesnt exist");
                Console.ReadLine();
                return;
            }
            else
            {
                //checks if the file exists and reads the contents of the file
                string path = Path.Combine(@"C:\Files\", param1);
                using (StreamReader reader = File.OpenText(path))
                {
                    string line = null;
                    do
                    {
                        line = reader.ReadLine();
                        Console.WriteLine(line);
                        Console.Read();
                    } while (line != null);
                }
                string path2 = "C:\Files\audit.txt";
                using (StreamWriter sw2 = File.AppendText(path2))
                {
                    sw2.WriteLine("User read " + param1 + " as: (should display contents of the file)""); //apend the text from the file into the audit log, and name from current login
                }
                Console.Read();
            }
            Console.ReadLine();
        }

以下是您可以执行此操作的方法:

using (StreamReader reader = File.OpenText(path1))
{
    using (StreamWriter writer = File.AppendText(path2))
    {
        writer.Write("User read " + param1 + " as: ");

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();

            //Console.WriteLine(line); //Uncomment this line if you want to write the line to the console

            writer.WriteLine(line);
        }
    }
}