1

I have created software that start's a program in my AppData folder.

What I wanted to do however is to let it run with a dynamic path.

The current path I used is:

new ProcessStartInfo(@"C:\Users\user\AppData\Local\SOFTWAREPROGRAM\File\program.exe")

I want it however to make it possible to not just run on 'user' but on all users with the AppData folder. I tried the following path (which works when browsing in directories):

new ProcessStartInfo(@"%USERPROFILE%\AppData\Local\SOFTWAREPROGRAM\File\program.exe")

With this however, I get the 'file not found'-error.

How would I correct this? I want it to work on different users.

EDIT

The answer works in my program but doesn't work in the service I'm trying to develop. I have tried:

(the answer)

new ProcessStartInfo(Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\AppData\Local\SOFTWAREPROGRAM\File\program.exe"))

and

string folder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string specificFile = Path.Combine(folder, @"\Local\SOFTWAREPROGRAM\File\program.exe");

ProcessStartInfo(specificFile)

This works in a program (console project) but not in a service. Why is this?

I output the specificFile while running but it only contains \Local\SOFTWAREPROGRAM\File\program.exe

Kahn Kah
  • 1,389
  • 7
  • 24
  • 49

1 Answers1

3

You can use Environment.ExpandEnvironmentVariables method to get the actual path from the environment variable.

new ProcessStartInfo(Environment.ExpandEnvironmentVariables(@"%USERPROFILE%\AppData\Local\SOFTWAREPROGRAM\File\program.exe"))
Pavel
  • 910
  • 5
  • 6
  • Pavel, I have edited the code in my service but your method seems not to work in services? – Kahn Kah Mar 23 '17 at 12:42
  • What account does you service use to run? Typically services run under special system account, e.g. Local Service or Network Service. But you can specify any Windows account to run it. – Pavel Mar 23 '17 at 12:46
  • If I used the old method (the absolute path with `C:\Users\Administrator`, it used `SYSTEM`, and that's what I'm trying to achieve – Kahn Kah Mar 23 '17 at 12:47
  • 1
    %USERPROFILE% if the path to the folder of the user running the application. So it's the profile folder of the SYSTEM user in your case. – Pavel Mar 23 '17 at 12:50
  • So I need to replace `USERPROFILE` with `SYSTEM` to get it working in Services? – Kahn Kah Mar 23 '17 at 12:51
  • 1
    No. You have the following options: 1) put the application you want to run into the SYSTEM user profile folder (it seems to be C:\Windows\System32\Config\systemprofile), but it's not a good idea; 2) run your service under a different account 3) search the registry to get the profile folder of the specific user 4) use impersonation to access the specific user's folder. 5) put the application you want to run into the ProgramData folder, so it is available for all users. I think, variants 4 and 5 are the best ones. – Pavel Mar 23 '17 at 13:00