I'm writing a program that copies the FAT to a file (and restores it). I'm using CreateFile
to open a drive letter as a file, SetFilePointerEx
to seek to 0 position, ReadFile
to read the contents of the drive, and WriteFile
to write to the drive.
Using this strategy I can basically copy the entire drive. However, how should I know where to start and when to stop? Basically, what I want to know is the location of the beginning and the end of File Allocation Table in an exFAT disk.
Here's the code that I use to run the backup for the first 4 GB of data:
private static void RunBackup(string driveLetter)
{
IntPtr handle = CreateFile(
string.Format("\\\\.\\{0}:", driveLetter),
FileAccess.Read,
FileShare.Read,
IntPtr.Zero,
(FileMode)OPEN_EXISTING,
0,
IntPtr.Zero);
// Set offset
uint chunks = 100;
uint bufferSize = 512 * chunks;
long pt = 0;
byte[] buffer = new byte[bufferSize];
SetFilePointerEx(
handle,
0,
ref pt,
0);
long oneGB = 1073741824;
var backupSize = oneGB * 4;
var loops = backupSize / bufferSize;
Console.WriteLine($"Expecting {loops:N0} loops.");
uint read = 0;
using (var writer = new BinaryWriter(File.OpenWrite(@"D:\\fat.backup")))
{
for (int i = 0; i < loops; i++)
{
ReadFile(
handle,
buffer,
bufferSize,
ref read,
IntPtr.Zero);
writer.Write(buffer);
writer.Flush();
Console.Write($"\rLoop: {i:N0}");
}
writer.Close();
}
CloseHandle(handle);
}