且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#:追加*内容*一个文本文件到另一个文本文件

更新时间:2023-11-27 22:04:22

没有,我不认为有任何事情做到这一点。

No, I don't think there's anything which does this.

如果两个文件使用相同的编码,你不需要验证它们是有效的,你可以把它们作为二进制文件,如:

If the two files use the same encoding and you don't need to verify that they're valid, you can treat them as binary files, e.g.

using (Stream input = File.OpenRead("file1.txt"))
using (Stream output = new FileStream("file2.txt", FileMode.Append,
                                      FileAccess.Write, FileShare.None))
{
    input.CopyTo(output); // Using .NET 4
}
File.Delete("file1.txt");

请注意,如果 FILE1.TXT 包含字节顺序标记,你应该跳过这首以避免它 FILE2.TXT 的中间。

Note that if file1.txt contains a byte order mark, you should skip past this first to avoid having it in the middle of file2.txt.

如果你不使用.NET 4,你甚至可以使用扩展方法写你自己的 Stream.CopyTo ...相当于使交接无缝的:

If you're not using .NET 4 you can write your own equivalent of Stream.CopyTo... even with an extension method to make the hand-over seamless:

public static class StreamExtensions
{
    public static void CopyTo(this Stream input, Stream output)
    {
        if (input == null)
        {
            throw new ArgumentNullException("input)";
        }
        if (output == null)
        {
            throw new ArgumentNullException("output)";
        }
        byte[] buffer = new byte[8192];
        int bytesRead;
        while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, bytesRead);
        }
    }
}