Skip to content

Instantly share code, notes, and snippets.

@mjs3339
Created September 6, 2018 00:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mjs3339/e8de4606bf8be71b3ee5cec10cd7e03e to your computer and use it in GitHub Desktop.
Save mjs3339/e8de4606bf8be71b3ee5cec10cd7e03e to your computer and use it in GitHub Desktop.
C# CopyFileEX Copy Physical Sectors and Write to a Logical File
public bool CopyFileEx(string sourceFile, string targetFile)
{
long bytesLeft = 0;
long bytesProcessed = 0;
long sectorsCopied = 0;
var fileinfo = new FileInfo(sourceFile);
var fileFragments = FileFragments.GetFileAllocation(sourceFile);
if(fileFragments.TotalFragments == 0 || fileinfo.Length == 0)
return false;
var device = new Device(512);
device.OpenDeviceForReading(sourceFile[0].ToString(), Device.ODDevType.Logical);
using(var stream = new FileStream(targetFile, FileMode.Create, FileAccess.Write, FileShare.Write, 4096, true))
{
for(var i = 0; i < fileFragments.TotalFragments; i++)
{
foreach(var e in fileFragments.FileAllocation)
{
var Sector = e.StartingSector;
do
{
var buf = device.ReadSector(Sector);
if(fileinfo.Length < 512)
{
stream.Write(buf, 0, (int) fileinfo.Length);
goto Tag1;
}
stream.Write(buf, 0, 512);
bytesProcessed += 512;
bytesLeft = fileinfo.Length - bytesProcessed;
if(bytesLeft != 0)
if(bytesLeft < 512)
{
buf = device.ReadSector(Sector + 1);
stream.Write(buf, 0, (int) bytesLeft);
goto Tag1;
}
Sector++;
sectorsCopied++;
if(sectorsCopied > e.NumberOfSectors)
{
sectorsCopied = 0;
break;
}
if(bytesLeft <= 0)
break;
} while(bytesLeft > 0);
}
if(bytesLeft <= 0)
break;
}
}
Tag1:
device.CloseInDevice();
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment