Skip to content
Mahmudul Hasan

How to Store and Retrieve Environment Variable in C#

Tips & Tricks, CSharp, Azure1 min read

I know this is not a new topic. But I have seen many developers who are not aware of this. So, I thought it would be a good idea to write a post about it. Because storing secret information in env variable is very handy during development.

But before we start, let me tell you what is an environment variable. In simple words, an environment variable is a dynamic string value that gets stored in the system and can be accessed by any program. It's use case can be diverse. For example, you can use it to store a database connection string, API key, or any other secret information instead of hardcoding it in your code. If you are using any code collaboration tool like GitHub, this can be very useful since you don't want the world to take care of your credentials.

Enough of the theory. Let's see how to store and retrieve environment variable in C#.

To Store Environment Variable

1Environment.SetEnvironmentVariable("MyVariable", "MyValue");
2
3// To store it for the current user only, use the following code.
4// Environment.SetEnvironmentVariable("MyVariable", "MyValue", EnvironmentVariableTarget.User);

Alternatively, you can also use the terminal to store environment variable. For example, if you are using Windows, you can use the following command to store an environment variable.

1setx MyVariable MyValue

Please note that. after you add the environment variable in Windows, you must start a new instance of the command window or any application that may use the it after creating the environment variable for the change to be detected.

If you are using Linux or macOS, you can use the following command to store an environment variable.

1export MyVariable=MyValue

To Retrieve Environment Variable

1Environment.GetEnvironmentVariable("MyVariable");

To retrieve environment variable in the terminal, and if you are using Windows, you can use the following command to retrieve an environment variable.

1gci env:MyVariable

If you are using Linux or macOS, you can use the following command to retrieve an environment variable.

1echo $MyVariable

To Retrieve All Environment Variables

1Environment.GetEnvironmentVariables();

To retrieve all environment variables in the terminal, and if you are using Windows, you can use the following command to retrieve all environment variables.

1gci env:* | select Name,Value

If you are using Linux or macOS, you can use the following command to retrieve all environment variables.

1env

Conclusion

That's all for today. I hope you have learned something new today. If you have any questions, please feel free to ask in the comment section below. I will try my best to answer them. Just kidding 🤣. I don't have a comment section.

© 2024 by Mahmudul Hasan. All rights reserved.