c# open file, path starting with %userprofile%

C#File

C# Problem Overview


I have a simple problem. I have a path to a file in user directory that looks like this:

%USERPROFILE%\AppData\Local\MyProg\settings.file

When I try to open it as a file

ostream = new FileStream(fileName, FileMode.Open);

It spits error because it tries to add %userprofile% to the current directory, so it becomes:

C:\Program Files\MyProg\%USERPROFILE%\AppData\Local\MyProg\settings.file

How do I make it recognise that a path starting with %USERPROFILE% is an absolute, not a relative path?

PS: I cannot use

Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)

Because I need to just open the file by its name. User specifies the name. If user specifies "settings.file", I need to open a file relative to program dir, if user specifies a path starting with %USERPROFILE% or some other thing that converts to C:\something, I need to open it as well!

C# Solutions


Solution 1 - C#

Use Environment.ExpandEnvironmentVariables on the path before using it.

var pathWithEnv = @"%USERPROFILE%\AppData\Local\MyProg\settings.file";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);

using(ostream = new FileStream(filePath, FileMode.Open))
{
   //...
}

Solution 2 - C#

Try using ExpandEnvironmentVariables on the path.

Solution 3 - C#

Use the Environment.ExpandEnvironmentVariables static method:

string fileName= Environment.ExpandEnvironmentVariables(fileName);
ostream = new FileStream(fileName, FileMode.Open);

Solution 4 - C#

I use this in my Utilities library.

using System;
namespace Utilities
{
    public static class MyProfile
   {
        public static string Path(string target)
        {
            string basePath = 
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile) + 
@"\Automation\";
            return basePath + target;
        }
    }
}

So I can simply use e.g. "string testBenchPath = MyProfile.Path("TestResults");"

Solution 5 - C#

You can use the Environment.Username constant as well. Both of the %USERPROFILE% and this Environment variable points the same( which is the currently logged user). But if you choose this way, you have to concatenate the path by yourself.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIstrebitelView Question on Stackoverflow
Solution 1 - C#OdedView Answer on Stackoverflow
Solution 2 - C#Andras ZoltanView Answer on Stackoverflow
Solution 3 - C#David MView Answer on Stackoverflow
Solution 4 - C#john rainsView Answer on Stackoverflow
Solution 5 - C#NeverJrView Answer on Stackoverflow