title: IOException "Cyclic Rendundancy Check" FileStream.CopyTo using C#.Net
body: <p>I have some C# code that uses FileStreams to open a PhysicalDrive and take an image of the whole disk, but s consistently throwing an IOException with the message "Data error (cyclic redundancy check)." After copying about 121MB of a 128MB disk.</p>
  
  <pre><code>    using Microsoft.Win32.SafeHandles;
      using System.IO;
      using System;
  
      [DllImport("kernel32.dll", CharSet = CharSet.Auto, CallingConvention = CallingConvention.StdCall, SetLastError = true)]
      protected static extern SafeFileHandle CreateFile(
          string lpFileName,
          uint dwDesiredAccess,
          uint dwShareMode,
          IntPtr SecurityAttributes,
          uint dwCreationDisposition,
          uint dwFlagsAndAttributes,
          IntPtr hTemplateFile
      );
  
  public void MakeImage() 
  {
  
      SafeFileHandle TheDevice = null;
      try
      {
      TheDevice = CreateFile(@"\\.\PHYSICALDRIVE1", (uint)FileAccess.Read, (uint)0, IntPtr.Zero, (uint)FileMode.Open, (uint)FILE_ATTRIBUTE_SYSTEM, IntPtr.Zero);
          if (TheDevice.IsInvalid) { throw new IOException("Unable to access drive. Win32 Error Code " + Marshal.GetLastWin32Error()); }
          using (FileStream Dest = System.IO.File.Open("output.bin", FileMode.Create))
          {
              using (FileStream Src = new FileStream(TheDevice, FileAccess.Read))
              {
                  Src.CopyTo(Dest);
                  Src.Close();
              }
              Dest.Close();
          }
      }
      catch(Exception Ex)
      {
          //Here is where i am getting the IOException
          //Handle error..
      }
      finally
      {
          if (TheDevice != null)
          {
              if (!TheDevice.IsClosed)
                  TheDevice.Close();
              TheDevice.Dispose();
          }
      }
  }
  </code></pre>
  
  <p>I have run Scan Disk on the Drive in question and there doesn't appear to be anything wrong with it. If I change the first Param of CreateFile to just read a partition (not what I want to do), then the image is created fine.</p>
  
  <p>This is a follow up to <a href="https://stackoverflow.com/questions/7092331/windows-c-implementation-of-linux-dd-command">Windows C# implementation of linux dd command</a> that I've been trying to do.</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>Further investigations show that the error has something do with not being able to get or know the Src.Length property. I changed my code to copy byte by byte and keep a count, it errors after 126959616 bytes, which is 1 byte more than the total size of the image produced by dd.</p>