Softmochi
Softmochi

Reputation: 119

Reading a file path from text file with environment variable in C#

I am trying to read a text file with file paths, but the problem I'm having is I want to add environment variable in it with the specific file path, how should I achieve that? I tried to do %example123%+\XML\sample.xml but c# is not recognizing the variable instead it's reading it as a String.

Upvotes: 2

Views: 2375

Answers (3)

Tonkleton
Tonkleton

Reputation: 547

Two options, per your example:

System.Environment.GetEnvironmentVariable("example123") + @"\XML\sample.xml"

or

System.Environment.ExpandEnvironmentVariables(@"%example123%\XML\sample.xml")

Something to note from this question is that Visual Studio must be restarted before the variable is recognized if you have set the variable using System.Environment.SetEnvironmentVariable().

Upvotes: 2

SurrealSyntax
SurrealSyntax

Reputation: 1375

These two methods should help you in getting or setting environment variables.

System.Environment.GetEnvironmentVariable ()

and

System.Environment.SetEnvironmentVariable()

Either use them in your path variable or declare it separately, whichever is more readable.

Note: When using the SetEnvironmentVariable() sometimes you would have to restart visual studio to be able to read the environment variable after creating it.

Upvotes: 5

Jon Tirjan
Jon Tirjan

Reputation: 3694

Here's an example for %AppData%

System.Environment.GetEnvironmentVariable("AppData");

Upvotes: 0

Related Questions