开发者

.NET on linux, ~/folder is wrong?

开发者 https://www.devze.com 2023-01-08 11:50 出处:网络
In .NET i am writing Directory.CreateDirectory(textBox4.Text); textBox4.Text is ~/myfolder. What i get is a folder in the current wor开发者_StackOverflow中文版king directory called ~ with myfolder

In .NET i am writing

Directory.CreateDirectory(textBox4.Text);

textBox4.Text is ~/myfolder. What i get is a folder in the current wor开发者_StackOverflow中文版king directory called ~ with myfolder in it. How do i have CreateDirectory create myfolder at the user's home?


Tilde expansion is normally handled by the shell (http://www.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_01).

You could do something like bash -c "echo ~/folder" and grab the output. I'm not familiar with a .NET API (or even a C API) that does this, though I have to imagine that one is out there somewhere.

I take that back - the glob() C runtime function (on Linux) will take a GLOB_TILDE flag to perform this expansion.


I end up using this

    string GetHome()
    {
        string homePath = (Environment.OSVersion.Platform == PlatformID.Unix ||
               Environment.OSVersion.Platform == PlatformID.MacOSX)
? Environment.GetEnvironmentVariable("HOME")
: Environment.ExpandEnvironmentVariables("%HOMEDRIVE%%HOMEPATH%");
        return homePath;
    }

        var saveDirectory = textBox4.Text;
        if (saveDirectory.StartsWith("~/"))
            saveDirectory = GetHome() + saveDirectory.Substring(1);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号