How to specify username when referencing directory in C#

时间:2019-04-08 13:17:22

标签: c#

Essentially I am trying to create a C# program that goes into a local directory and performs some tasks by executing a batch file. The batch file itself is located in the AppData Roaming table and requires the C# program to know the username of the computer, whatever it may be.

This is what I currently have:

static void Main()
{
    ProcessStartInfo processInfo = new ProcessStartInfo("C:\\Users\\%username%\\AppData\\Roaming");
    processInfo.WindowStyle = ProcessWindowStyle.Hidden;
    processInfo.CreateNoWindow = true;
    processInfo.UseShellExecute = true;
    Process batchProcess = new Process();
    batchProcess.StartInfo = processInfo;
    batchProcess.Start();
}

Notice how I've added %username% but it doesn't seem to understand environmental variables.

What can I add to my code?

My code is not exactly a duplicate as the use case is entirely different, I am referencing the app data roaming directory and opening a batch located in it.

1 个答案:

答案 0 :(得分:0)

You can get the user folder for the current user like this:

string userfolder = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);

And so the path you want would be like:

string path = Path.Combine(userfolder, "AppData\\Roaming");
ProcessStartInfo processInfo = new ProcessStartInfo(path);