日期:2014-05-17  浏览次数:20969 次

C#文件读写,需要MD5值一样 求解
下面是我写的代码,问题也在代码中注解

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Collections.Specialized;
using System.Runtime.Remoting.Messaging;
using System.IO;


namespace test3
{
  
  class Program
  {

  static void Main(string[] args)
  {
  FileStream fs = new FileStream(@"c:\A.rar", FileMode.Open);

  FileStream fs2 = new FileStream(@"c:\2.rar", FileMode.Create);
  // 1.当 int bufferSize = 1;时,复制出来的文件是一样的,也就是说MD5是相同的
  // 2.当int bufferSize = 1024;时,复制出来的文件MD5值不同了。
  //我需要第二种方法,有什么方法可以解决此问题
  //因为第一种方法对于大文件变态的耗时了。
  int bufferSize = 1024;
  byte[] buffer = new byte[bufferSize];
  int read = 0;
  int hasRead = 0;
  fs.Position = 0;
  fs2.Position = 0;
  while (fs.Position < fs.Length)
  {
  read = fs.Read(buffer, 0, bufferSize);
  fs2.Write(buffer, 0, bufferSize);
  fs2.Flush();
  fs2.Position = fs2.Position;
  //hasRead += read;
  //Console.WriteLine("complete "+hasRead .ToString ());
  //Thread.Sleep(100);
  }

  Console.ReadKey();
  }
  }
}



------解决方案--------------------
while (fs.Position < fs.Length)
{
read = fs.Read(buffer, 0, bufferSize);
fs2.Write(buffer, 0, read);
fs2.Flush();
fs2.Position = fs2.Position;
//hasRead += read;
//Console.WriteLine("complete "+hasRead .ToString ());
//Thread.Sleep(100);
}
自己看红色部分,修改下就没问题了。
------解决方案--------------------
探讨
while (fs.Position < fs.Length)
{
read = fs.Read(buffer, 0, bufferSize);
fs2.Write(buffer, 0, read);
fs2.Flush();
fs2.Position = fs2.Position;
//hasRead += read;
//Console.WriteLi……