使用Path.Combine()在Windows系统上形成Linux路径 [英] Using Path.Combine() to form a Linux path on a Windows system
本文介绍了使用Path.Combine()在Windows系统上形成Linux路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在用C#编写一个应用程序,该应用程序将在Windows下编译和运行,但部分负责将文件上传到Linux服务器上的文件夹结构.在Windows应用程序中,我希望能够轻松地将Linux目录和文件名与Path.Combine结合在一起.有没有办法使用其他路径分隔符临时覆盖Path.Combine?
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?
推荐答案
如果只想合并,那是我的解决方法
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"
这篇关于使用Path.Combine()在Windows系统上形成Linux路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文