Mega Code Archive

 
Categories / Delphi / Graphic
 

Creating and restoring images of drives

Title: Creating and restoring images of drives? Question: How do you create an image of a drive, and then later restore it? Windows does most of it for you already! Answer: I recently was using boot disk images a lot from www.bootdisk.com, and pondered how such images were made. On UNIX systems you can use dd, something like dd /mnt/fd0/ /disk.img - alas on Windows it isn't so straight forward. CreateFile() is the answer here, it does everything you need. For the example below, we're going to image A: to DISK.IMG: procedure ImageDisk; var InF, OutF: THandle; Buffer: array [1..(1024 * 64)] of Byte; // 64kb buffer BufRead, BufWrote: DWORD; begin InF := CreateFile('\\.\A:',GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); OutF := CreateFile('DISK.IMG',GENERIC_WRITE,FILE_SHARE_READ,nil,CREATE_ALWAYS,0,0); BufRead := 1; while (ReadFile(InF,Buffer,SizeOf(Buffer),BufRead,nil) = True) and (BufRead 0) do begin WriteFile(OutF,Buffer,BufRead,BufWrote,nil); end; CloseHandle(OutF); CloseHandle(InF); end; That's all it is! Simple or what... How to restore the DISK.IMG back to floppy? procedure RestoreImage; var InF, OutF: THandle; Buffer: array [1..(1024 * 64)] of Byte; // 64kb buffer BufRead, BufWrote: DWORD; begin InF := CreateFile('DISK.IMG',GENERIC_READ,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); OutF := CreateFile('\\.\A:',GENERIC_WRITE,FILE_SHARE_READ,nil,OPEN_EXISTING,0,0); // Make sure the image will fit the disk if GetFileSize(OutF,nil) begin CloseHandle(InF); CloseHandle(OutF); Exit; end; BufRead := 1; while (ReadFile(InF,Buffer,SizeOf(Buffer),BufRead,nil) = True) and (BufRead 0) do begin WriteFile(OutF,Buffer,BufRead,BufWrote,nil); end; CloseHandle(OutF); CloseHandle(InF); end; See, very easy. This just does the floppy disk drive, however I personally used ImageDisk on my CD drive (replace \\.\A: with \\.\D: (D: being you CD-ROM drive) ) and it created a nice plain vanilla ISO image for me. You can also use for example ZLIB to compress the DISK.IMG making it nice and small! This routine can also be used to COMPLETELY erase a disk, just write a preset buffer of $00 to the max file size! CreateFile() also works on hard drives and partitions! Have fun! --- Ammendments --- 13/11/2001: CreateFile() only works on non hard drives (i.e floppy, zip...) under Windows 9x, however a nice guy developed a low level unit to let you have just as much fun, you can download it from: http://www.workshell.co.uk/dev/delphi/DejanMaksimovicAlfa32.zip As I didn't write this unit I take no responsibility for its use - nor will I offer support, though I may write an article on using it in the future.