C#:追加*内容*一个文本文件到另一个文本文件 [英] C#: Appending *contents* of one text file to another text file

查看:697
本文介绍了C#:追加*内容*一个文本文件到另一个文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有可能是没有其他办法可以做到这一点,但有没有办法一个文本文件的内容追加到另一个文本文件中,而移动后清除第一?

There is probably no other way to do this, but is there a way to append the contents of one text file into another text file, while clearing the first after the move?

我知道的唯一方法是只使用一个读者和作家,这似乎是低效的大文件...

The only way I know is to just use a reader and writer, which seems inefficient for large files...

谢谢!

推荐答案

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

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

这篇关于C#:追加*内容*一个文本文件到另一个文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆