How to skip the VirtualStore and read files in Program Files folder?

3.3k Views Asked by At

I have a c# application on Windows 10 PC. There are settings files in the install folder (C:\Program Files (x86)\xxx) which I want to read, but not edit unless user has admin access. The problem is that windows is copying these settings files to the VirtualStore and redirecting all reads there - whereas the same app run as admin sees the original settings files in the Program Files folder.

My question: Is there a way to make the application see the original files in the Program Files even when not run as admin? I just want to read them, not edit them.

2

There are 2 best solutions below

3
On BEST ANSWER

You don't need elevated permissions to read the file from Program Files (x86) folder. Check how you open the file for reading. You should specify different FileAccess flag in common user mode and in elevated mode. For common user mode it should be opened with 'FileAccess.Read`:

using (FileStream settingsFile = new FileStream(@"C:\Program Files (x86)\xxx", FileMode.Open, FileAccess.Read))
{
  // Do the job
}

To detect if application runs with elevated permissions use IsProcessElevated method. Depending on the result you are able to select proper FileAccess mode.

0
On

The way to see original files in Program Files is to not write there (and to that end open files for read-only as Nikita points out). The VirtualStore is not there to be used, but to fix application issues. Such issues are caused for example by broken applications written for old single user Windows when current day Windows (since NT) can have multiple sessions concurrently from different users.

If an application wants to modify data files shared between all users, it should save the files to All Users Profile. If it is user data, it can store the data in Application Data folder in the user profile. In the Application Data you are still left with the option if you want the data to be Roaming or Local.

The paths to these folders are different on different Windows versions. Windows Installer has properties set to the paths. Applications have many interfaces they can use. See Working with Known Folders in Applications and SHGetKnownFolderPath for one interface.

Other than that, the access to Program Files is behind UAC. You should read on it to get all details right.