How do I open a directory with CreateFile in C# to examine entries of deleted files? Or is it now impossible? I remember way back when being able to open a directory on an
I'm not sure what you mean by examining deleted directories, but you should be able to get a handle to a directory by passing the FILE_FLAG_BACKUP_SEMANTICS
flag into CreateFile
and by making sure to specify OPEN_EXISTING
for the creation disposition. From the MSDN article on CreateFile:
To open a directory using CreateFile, specify the
FILE_FLAG_BACKUP_SEMANTICS
flag as part of dwFlagsAndAttributes. Appropriate security checks still apply when this flag is used withoutSE_BACKUP_NAME
andSE_RESTORE_NAME
privileges.
It looks like you've previously tried some of this but commented it out? If this doesn't work for you, you might want to make sure that they the user you're running as has permission to acess the directory in question.
AFAIK, it's a fairly involved process. You can't just use CreateFile and enumerate the "deleted files". You have to load up the master file table of the drive, and enumerate that for files marked deleted, and then try to load the data from the disk position listed in the MFT. This would require a lot of Platform Invoked code, and probably a few redefinitions of native data structures in C#.
The short answer to your question is this:
CreateFile("\\\\.\\PhysicalDrive0",
GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_WRITE,
0,
OPEN_EXISTING,
0,
NULL)
You use create file to open the disk itself.
Here is a really good article about the whole process on Code Project. But, it's all in c++. The code is there, and it seems you know how to p\invoke, so porting it over shouldn't be a problem.
Edit:
The fact that drive is external shouldn't make it any harder, you can still open the disk the same way I showed (maybe use a WMI tool to look up the path once the drive is connected). Then, you can use the information on the Wikipedia page for FAT32 to define data structures that you can read the MFT and other pieces of the file system into. Once you get there, you just iterate through the 32 byte file definitions in the directory table looking at the first byte for:
0xE5 Entry has been previously erased and is available. File undelete utilities must replace this character with a regular character as part of the undeletion process.
Just to throw another approach at you, in case it's relevant, you could always just watch the directory with a FileSystemWatcher and catch the Deleted
event. Of course, you'll need to be watching it at the time of deletion, but it may be a far easier solution then trying to recover it (if it's an option).