克隆文件并修改它

Clone a file and modify it

我是 C# 的新手,我只想将它用于一个项目。 我想编写一个程序来读取一些文件并逐行克隆它们。 如果一行是触发器,它将调用一个函数,该函数将添加一些其他行而不是原始行。

我发现了如何通过 ms 帮助(官方代码片段)逐行读取文件,但是当我尝试在其中写入时,它只写入了最后一行,我猜删除了其余部分。我尝试了以下但没有成功。 它应该只是创建一个新文件并覆盖如果已经有一个,每行写一行。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int counter = 0;
            string line;

            // Read the file and display it line by line.
            System.IO.StreamReader file =
                new System.IO.StreamReader(@"c:\test.txt");
            while ((line = file.ReadLine()) != null)
            {
                using (StreamWriter outfile = new StreamWriter(@"c:\test2.txt"))
                outfile.write(line);
                counter++;
            }

            file.Close();
            System.Console.WriteLine("There were {0} lines.", counter);
            // Suspend the screen.
            System.Console.ReadLine();
        }
    }
}

问题是您在 次迭代中打开输出文件。相反,您应该同时打开两个文件:

using (var reader = File.OpenText(@"c:\test.txt"))
{
    using (var writer = File.CreateText(@"c:\test2.txt"))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            // Handle triggers or whatever
            writer.WriteLine(line);
        }
    }
}

它不会删除你写的东西,它会覆盖它。您需要以附加模式打开流编写器:

StreamWriter outfile = new StreamWriter(@"c:\test2.txt", true)

但我会避免每次都打开 streamwriter,打开一次并确保刷新或关闭它。