Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET File.Exists doesn't work in Windows\System32\Drivers folder?

The process is elevated and I ensured that the path was correct in VS debugger (I'm using Environment.GetFolderPath(Environment.SpecialFolder.System) not hard coding it in) but File.Exists still returns false.

The reason I need this is a workaround for ensuring some 3rd party drivers are installed because their registry settings aren't removed on uninstall.

I know writes are redirected via virtualization but is this also true for checking a file's existence?

like image 894
Davy8 Avatar asked May 26 '09 20:05

Davy8


1 Answers

Yes, virtualization happens at a very low level. The File.Exists method basically calls the Win32 CreateFile method and checks for errors. CreateFile is redirected by the WOW subsystem.

You can disable virtualization temporarily before calling.

[DllImport( "kernel32", CharSet=CharSet.Unicode, SetLastError=true )]
public static extern bool Wow64DisableWow64FsRedirection( ref IntPtr oldValue );

[DllImport( "kernel32", CharSet=CharSet.Unicode, SetLastError=true )]
public static extern bool Wow64RevertWow64FsRedirection( IntPtr oldValue );

Of course to be complete you'll have to check for file existence with virtualization on as well as off. The same applies for checking registry entries as well.

public static bool FileExists( string path )
{
    if( File.Exists( path ) ) return true;
    IntPtr oldValue = IntPtr.Zero;
    try
    {
        if( Environment.GetEnvironmentVariable( "PROCESSOR_ARCHITEW6432" ) == null )
            return false;

        Wow64DisableWow64FsRedirection( ref oldValue );
        if( File.Exists( path ) ) return true;

        return false;
    }
    finally
    {
        if( oldValue != IntPtr.Zero )
            Wow64RevertWow64FsRedirection( ref oldValue );            
    }   
}

Update: You may also need to check the OS version before disabling the WOW redirection because earlier versions of XP (Pre SP2 I believe) do not expose those methods.

Update 2: Added OS check for 64-bit. All 64-bit versions of the OS implement these methods and you only need to disable the sate if running on a 64-bit OS.

like image 118
Paul Alexander Avatar answered Oct 24 '22 11:10

Paul Alexander