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

时间:2015-12-01 18:54:15

标签: c# append filereader streamreader

我正在编写一个命令方法,该方法读取txt文件的内容,并且如果文件名已经使用,则进行正确的检查,如果存在,等等。

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

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

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

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

1 个答案:

答案 0 :(得分:1)

以下是如何执行此操作的方法:

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