Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

c# - Using Path.Combine() to form a Linux path on a Windows system

I am writing an application in C# which will be compiled and run under Windows but which will, in part, be responsible for uploading files to a folder structure on Linux servers. In my Windows application I would like to be able to easily combine Linux directories and file names together with Path.Combine. Is there a way to temporarily override Path.Combine with a different path separator?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you only want combine, there is my solution

public static string PathCombine(string pathBase, char separator = '/', params string[] paths)
{
    if (paths == null || !paths.Any())
        return pathBase;

    #region Remove path end slash
    var slash = new[] { '/', '\' };
    Action<StringBuilder> removeLastSlash = null;
    removeLastSlash = (sb) =>
    {
        if (sb.Length == 0) return;
        if (!slash.Contains(sb[sb.Length - 1])) return;
        sb.Remove(sb.Length - 1, 1);
        removeLastSlash(sb);
    };
    #endregion Remove path end slash

    #region Combine
    var pathSb = new StringBuilder();
    pathSb.Append(pathBase);
    removeLastSlash(pathSb);
    foreach (var path in paths)
    {
        pathSb.Append(separator);
        pathSb.Append(path);
        removeLastSlash(pathSb);
    }
    #endregion Combine

    #region Append slash if last path contains
    if (slash.Contains(paths.Last().Last()))
        pathSb.Append(separator);
    #endregion Append slash if last path contains

    return pathSb.ToString();
}

With this, you can call

PathCombine("/path", paths: new[]{"to", "file.txt"});
// return "/path/to/file.txt"
PathCombine(@"\path", '\', "to", "file.txt");
// return @"\pathofile.txt"
PathCombine("/some/bin:paths/bin", ':', "/another/path", "/more/path");
// return "/some/bin:paths/bin:/another/path:/more/path"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...