Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

path

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?

like image 460
Larry Lustig Avatar asked Sep 26 '14 19:09

Larry Lustig


2 Answers

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"
like image 184
Kzas Avatar answered Nov 15 '22 19:11

Kzas


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('\\','/');
like image 2
meda Avatar answered Nov 15 '22 19:11

meda