C#打开文件,路径先从%USERPROFILE% [英] c# open file, path starting with %userprofile%
问题描述
我有一个简单的问题。我必须在用户目录中的文件看起来像这样的路径:
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);
这是因为它尝试添加吐奶误差%USERPROFILE%
到当前目录,所以就变成:
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
我如何使它认识到,与%USERPROFILE%
开始的路径是绝对的,而不是相对路径
How do I make it recognise that a path starting with %USERPROFILE%
is an absolute, not a relative path?
PS:我不能使用
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
由于我只是需要通过其名称打开该文件。用户指定的名称。如果用户指定settings.file,我需要打开一个文件相对于程序目录,如果用户指定使用%USERPROFILE%
启动或转换为其他一些事情的路径C:!\something,我需要打开它,以及
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!
推荐答案
使用的 Environment.ExpandEnvironmentVariables
使用它之前的路径。
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))
{
//...
}
这篇关于C#打开文件,路径先从%USERPROFILE%的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!