开发者

C#: Appending *contents* of one text file to another text file

There is probably no other way to do this, but is ther开发者_Go百科e 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...

Thanks!


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

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.

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


Ignoring error handling, encodings, and efficiency for the moment, something like this would probably work (but I haven't tested it)

File.AppendAllText("path/to/destination/file", File.ReadAllText("path/to/source/file"));

Then you just have to delete or clear out the first file once this step is complete.


The cmd.exe version of this is

type fileone.txt >>filetwo.txt

del fileone.txt

You could create a system shell to do this. It should be pretty effecient.


I'm not sure what you mean by "inefficient". Jon's answer is probably enough for most cases. However, if you are concerned about extremely large source files, Memory-Mapped Files could be your friend. See this link for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜