Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# open file, path starting with %userprofile%

Tags:

c#

file

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!

like image 876
Istrebitel Avatar asked Apr 03 '12 12:04

Istrebitel


2 Answers

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)) {    //... } 
like image 107
Oded Avatar answered Sep 27 '22 22:09

Oded


Try using ExpandEnvironmentVariables on the path.

like image 28
Andras Zoltan Avatar answered Sep 27 '22 21:09

Andras Zoltan