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

12,666

Solution 1

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 @"\\path\to\file.txt"
PathCombine("/some/bin:paths/bin", ':', "/another/path", "/more/path");
// return "/some/bin:paths/bin:/another/path:/more/path"

Solution 2

What you should do is create samba share directories.

This way you can just access it like a windows network path.

var path = @"\\"+linuxHostname + @"\sambaShare\";

But to answer your question you cannot change the Path.Combine slash .. maybe a string replace would do ?

var linuxPath = winPath.Replace('\\','/');
Share:
12,666
Larry Lustig
Author by

Larry Lustig

Freelance Windows / database programmer.

Updated on July 26, 2022

Comments

  • Larry Lustig
    Larry Lustig almost 2 years

    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?