本文介绍了如何写一个文件的内容复制到另一个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要编写一个文件的内容使用File.OpenRead和File.OpenWrite方法的另一个文件。我无法弄清楚如何做到这一点。
如何修改以下code为我工作。
使用(的FileStream流= File.OpenRead(C:\\ FILE1.TXT))
使用(的FileStream writeStream = File.OpenWrite(D:\\ FILE2.TXT))
{
读者BinaryReader在新= BinaryReader在(流);
的BinaryWriter作家=新的BinaryWriter(writeStream);
writer.Write(reader.ReadBytes(stream.Length));
}
解决方案
使用 (的FileStream流= File.OpenRead(C:\\ FILE1.TXT))
使用(的FileStream writeStream = File.OpenWrite(D:\\ FILE2.TXT))
{
读者BinaryReader在新= BinaryReader在(流);
的BinaryWriter作家=新的BinaryWriter(writeStream);
//创建一个缓冲区来保存字节
byte []的缓冲区=新的字节[1024];
INT读取动作;
//而读方法返回字节
//让他们写入到输出流
而((读取动作=
stream.Read(缓冲液,0,1024))> 0)
{
writeStream.Write(缓冲液,0,读取动作);
}
}
只是想知道为什么不使用这样的:
File.Copy(C:\\ FILE1.TXT,D:\\ FILE2.TXT);
I need to write contents of a file to another file using File.OpenRead and File.OpenWrite methods. I am unable to figure out how to do it.
How can i modify the following code to work for me.
using (FileStream stream = File.OpenRead("C:\\file1.txt"))
using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
{
BinaryReader reader = new BinaryReader(stream);
BinaryWriter writer = new BinaryWriter(writeStream);
writer.Write(reader.ReadBytes(stream.Length));
}
解决方案
using (FileStream stream = File.OpenRead("C:\\file1.txt"))
using (FileStream writeStream = File.OpenWrite("D:\\file2.txt"))
{
BinaryReader reader = new BinaryReader(stream);
BinaryWriter writer = new BinaryWriter(writeStream);
// create a buffer to hold the bytes
byte[] buffer = new Byte[1024];
int bytesRead;
// while the read method returns bytes
// keep writing them to the output stream
while ((bytesRead =
stream.Read(buffer, 0, 1024)) > 0)
{
writeStream.Write(buffer, 0, bytesRead);
}
}
Just wonder why not to use this:
File.Copy("C:\\file1.txt", "D:\\file2.txt");
这篇关于如何写一个文件的内容复制到另一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!