Reputation: 1
I have a strange issue using File.Exists in C#, reproducable on several PC's. I see it as an error in the .NET 4 library.
I use 7ZIP and automate it from a C# program, I call CreateProcess and zip and unzip files with it. For that, I need to find out if and where 7ZIP is installed, because I don't want to depend on PATH variables.
So this is part of the code:
if (File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\7-Zip\\7z.exe"))
clsGlobal.gstr_ZIP_PROG_MIT_PFAD = "\"" + Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles) + "\\7-Zip\\7z.exe\"";
else if (File.Exists("\"C:\\Program Files (x86)\\7-Zip\\7z.exe\""))
clsGlobal.gstr_ZIP_PROG_MIT_PFAD = "\"C:\\Program Files (x86)\\7-Zip\\7z.exe\"";
All Exist-Checks give me "false" back. The ProgramFiles-SpecialFolder points to the right (x86)-Folder, for sure. And also for sure, 7ZIP is installed in C:\Program Files (x86)\7-ZIP\7z.exe, and when calling CreateProcess, everything works fine. What can be the reason why all Exists() - Checks fail ? Is this a known bug ?
Upvotes: 0
Views: 2042
Reputation: 14608
I see it as an error in the .NET 4 library.
This is not a bug in the .NET Framework...
Print the path value.
It will be:
C:\Program Files (x86)\7-Zip\7z.exe
By default i believe 7-Zip
installs to Program Files
and not Program Files (x86)
.
You are using:
Environment.SpecialFolder.ProgramFiles
If your code is built to target x86 (i suspect it is) then this enum will give you:
Program Files (x86)
System.EnvironmentSpecialFolder
The program files directory.On a non-x86 system, passing ProgramFiles to the GetFolderPath method returns the path for non-x86 programs. To get the x86 program files directory on a non-x86 system, use the ProgramFilesX86 member.
Which is not the folder that 7-Zip
installs to.
If you change your code to read:
if (File.Exists(@"C:\Program Files\7-Zip\7z.sfx"))
You should be fine
Alternatively, target x64
and the enum will return the Program Files
string:
The path will now read:
C:\Program Files\7-Zip\7z.exe
Upvotes: 2
Reputation: 88
I would say that Dukeling is correct in his comment
"\"C:\\Program Files (x86)\\7-Zip\\7z.exe\""
is looking for a path starting with the double quotes BEFORE the C:\ As now he who must not be named said use the "@" before the string so it becomes:
@"C:\Program Files (x86)\7-Zip\7z.exe\"
This makes the code readable and also prevents any confusion with quotes which seems to be what is happening here.
Upvotes: 2