Copy text from one text file to another
Could someone demonstrate how to copy all lines of a text file to another one (without overwriting the destination fil开发者_如何学Ce, e.g.:
File A copies lines to File B (without overwriting the existing lines in FileB - adding them)
This looks like homework, so I'll just give you some pointers.
Open the first file with the FileMode.Open
and FileAccess.Read
parameters. Open the second file with FileMode.Append
and FileAccess.Write
parameters.
Loop through the first file, writing to the second one what you're reading from the first.
Look at the FileStream
class for more information.
Here is my solution. Hope it helps:
Dim fileAContent As String = ""
Using strR As New IO.StreamReader(fileAPath)
fileAContent = strR.ReadToEnd
End Using
Using strW As New IO.StreamWriter(fileBPath, True)
strW.Write(fileAContent)
strW.Flush()
End Using
Second parameter of StreamWriter is the key. It will append content to the end of file.
First read all lines from the first file and after that append all of them to second file.
Hope this answer helps you. I wrote it in a way that you can follow to give you a good understanding of the steps. To start, replace the files with yours then run the code to see if it gives you the result that you want.
var file1 = @"C:\Users\User\Desktop\file1.txt";
var file2 = @"C:\Users\User\Desktop\file2.txt";
var file1Lines = File.ReadAllLines(file1);
var file2Lines = File.ReadAllLines(file2).ToList();
// before the copy
Console.WriteLine("**Before the copy**");
Console.WriteLine(File.ReadAllText(file2));
foreach (var l in file1Lines)
{
file2Lines.Add(l);
}
File.WriteAllLines(file2, file2Lines);
// after the copy
Console.WriteLine("**After the copy**");
Console.WriteLine(File.ReadAllText(file2));
精彩评论