I have created a 32-bit application in C#. Because it's 32-bit, it cannot access 64-bit locations such as C:\Windows\System32. To access 64-bit locations, I understand that I need to instead use C:\Windows\Sysnative.
I want to check if a file exists in System32. I placed a file there and can view it in my file explorer, so I know that it exists.
However, when I use the following code, the File.Exists method always returns false. Sysnative doesn't seem to be redirecting at all. How can I use File.Exists with both %windir% and Sysnative to find a file in System32 from a 32-bit app?
string fileName = "someFile.dll";
string path = Environment.ExpandEnvironmentVariables(@"%windir%\Sysnative\" + fileName);
//path should be 'C:\Windows\System32\'+fileName;
bool fileExists = File.Exists(path); //Always returns false
I did a quick test and it turns out that if you are using x64 then fileExists
returns False
while it returns True
for x86 and Any CPU. As to the reason why, I don't know but since you plan on using this on a 32-bit application then simply use x86. Make sure to choose x86 so that Any CPU won't mistakenly pick x64.
eryksun:
The reason is simply that "SysNative" isn't a real directory. It gets redirected to the real "System32" directory by the WOW64 emulation system. Only 32-bit applications running on 64-bit Windows via WOW64 can use this virtual directory. A 32-bit application running on 32-bit Windows cannot use "SysNative", so "System32" has to be tried even in a 32-bit app.
CODE
class Program
{
static void Main(string[] args)
{
string fileName = "aeevts.dll";
string path = Environment.ExpandEnvironmentVariables(@"%windir%\Sysnative\" + fileName);
//path should be 'C:\Windows\System32\'+fileName;
Console.WriteLine(path);
bool fileExists = File.Exists(path); //Always returns false
Console.WriteLine(fileExists);
Console.Read();
}
}
Properties
OP
Running on Any CPU, only if you have 'prefer 32-bit' checked on the Platform Target (see above screenshot) will Sysnative work and the File.Exists returns true
x86/Any CPU Output
x64 Output