您的位置:首页 > 编程语言 > C#

用FileStream加byte[]字节数组缓冲区读写文件

2016-10-15 00:18 330 查看
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
//思路:就是现将要赋值的多媒体文件读取出来,然后希望如到你制定的位置
string source = @"D:\教程\1.txt";
string target = @"D:\教程\2.txt";
CopyFile(source, target);
Console.WriteLine("Copy Complete!");
Console.ReadKey();
}
public static void CopyFile(string source,string target)
{
//1。我们创建一个负责读取的流 fsRead
using(FileStream fsRead = new FileStream(source,FileMode.OpenOrCreate,FileAccess.Read))
//使用using语句减免代码,FileStream(src,mode,acs),节省Close() & Dispose()
{
//2.创建一个负责写入的流 fsWrite
using(FileStream fsWrite = new FileStream(target,FileMode.OpenOrCreate,FileAccess.Write))
//使用using语句减免代码,FileStream(src,mode,acs), 节省Close() & Dispose(),两个using嵌套,内部先Close() & Dispose()
{
byte[] buffer = new byte[1024*1024*5];
//因为文件可能会比较大,所以我们在读取的时候,应该通过一个循环去读取
while (true)//循环去读取写入
{
//返回本次实际读取到的字节数
int r = fsRead.Read(buffer, 0, buffer.Length);
//读取
//如果返回一个0,也就意味着什么都没有读取到,表示读取完了
if (r == 0)
{
break;
}
fsWrite.Write(buffer,0,r);
//写入
}

}
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C# IO File
相关文章推荐