一:分块写入文件
public static void GetDownLoad() { var url = @"C:UsersyouzikuDesktopASP.NET+MVC+4框架揭秘(蒋金楠).pdf"; var path = @"C:UsersyouzikuDesktoppdfmvc.pdf"; using (Stream s = new FileStream(url, FileMode.Open)) { using (Stream sm = new FileStream(path, FileMode.Create)) { //数据长度 var fileLength = s.Length; //数组长度 var partSize = 1024 * 1024; //计算循环次数 long count = GetCount(fileLength, partSize); for (int i = 0; i < count; i++) { var start = partSize * i; //剩余长度 var sxLength = fileLength - start; //建立一个标准长度的byte数组 byte[] bt = new byte[partSize]; if (sxLength > partSize) { //向数组中读取数据 s.Read(bt, 0, partSize); } else { //剩余长度不够时,重新建立一个byte数组 bt = new byte[sxLength]; s.Read(bt, 0, Convert.ToInt32(sxLength)); } //写入 sm.Write(bt, 0, bt.Length); } sm.Flush(); sm.Close(); } } Console.WriteLine("执行完成"); }
二:多线程分块写入文件
//获取文件流 public void GetDown() { var url = @"D:office办公cn_office_professional_plus_2013_x64_dvd_1134006.iso"; Stream rs = new FileStream(url, FileMode.Open); //平均每次写入的量 PartSizeNormal = rs.Length / 10; //最后一次把全部数据都写入 if (rs.Length % 10 != 0) { PartSizeLast = rs.Length - PartSizeNormal * 9; } //线程池 for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(new WaitCallback(WriteFile), rs); } } //创建写入文件 Stream st = new FileStream(@"C:UsersyouzikuDesktoppdfoffice.iso", FileMode.Create); //写入文件 public void WriteFile(object o) { Stream s = o as Stream; Interlocked.Add(ref ck, 1); byte[] by = new byte[PartSizeNormal]; //最后一次写入 if (ck == 10) { by = new byte[PartSizeLast]; } s.Read(by, 0, by.Length); st.Write(by, 0, by.Length); st.Flush(); }