有你在真好 的个人博客
DotNet处理服务器路径的方法
阅读:2287 添加日期:2021/3/27 23:27:48 原文链接:https://www.toutiao.com/item/6343474937281380866/

项目中需要使用到路径处理的地方比较多,对于路径的解析和匹配有时较为繁琐,现在提供一个对路径进行解析的方法:

1.验证设置路径字符串:

/// <summary>

/// 验证设置路径字符串

/// </summary>

/// <param name="path">路径字符串</param>

/// <param name="isSequential">如果正在创建路径</param>

static public void ValidatePath(string path, bool isSequential)

{

ValidatePath(isSequential ? path + "1" : path);

}

/// <summary>

/// 验证设置路径字符串

/// </summary>

/// <param name="path">路径字符串</param>

/// <exception cref="ArgumentException">路径无效</exception>

static public void ValidatePath(string path)

{

if (path == null)

throw new ArgumentException("路径不能为空");

if (path.Length == 0)

throw new ArgumentException("路径长度必须大于0");

if (path[0] != '/')

throw new ArgumentException("路径必须启动/字符");

if (path.Length == 1) return;

if (path[path.Length - 1] == '/')

throw new ArgumentException("路径不能结束与/字符");

string reason = null;

var lastc = '/';

var chars = path.ToCharArray();

for (var i = 1; i < chars.Length; lastc = chars[i], i++)

{

var c = chars[i];

if (c == 0) { reason = "不允许空字符 @" + i; break; }

if (c == '/' && lastc == '/') { reason = "指定的空节点名称@" + i; break; }

if (c == '.' && lastc == '.')

{

if (chars[i - 2] != '/' || ((i + 1 != chars.Length) && chars[i + 1] != '/')) continue;

reason = "不允许的相对路径 @" + i;

break;

}

if (c == '.')

{

if (chars[i - 1] != '/' || ((i + 1 != chars.Length) && chars[i + 1] != '/')) continue;

reason = "不允许的相对路径 @" + i;

break;

}

if ((c <= '\u0000' || c >= '\u001f') && (c <= '\u007f' || c >= '\u009F') &&

(c <= '\ud800' || c >= '\uf8ff') && (c <= '\ufff0' || c >= '\uffff')) continue;

reason = "无效的字符 @" + i;

break;

}

if (reason != null) throw new ArgumentException(string.Format("无效的路径字符串 \"{0}\" 引起的 {1}", path, reason));

}

2.查看服务器的路径:

/// <summary>

/// 在目录到客户端的路径(如果有的话)。期望

///此功能是客户端路径已在此之前验证

////调用/函数调用

/// </summary>

/// <param name="chroot"></param>

/// <param name="clientPath">节点的路径。</param>

/// <returns>查看服务器的路径(chroot添加到客户端的路径)</returns>

static public string PrependChroot(string chroot, string clientPath)

{

if (string.IsNullOrEmpty(chroot)) return clientPath;

return clientPath.Length == 1 ? chroot : string.Concat(chroot, clientPath);

}

3.删除目录:

/// <summary>

/// 删除目录

/// </summary>

/// <param name="chroot"></param>

/// <param name="serverPath"></param>

/// <returns></returns>

static public string RemoveChroot(string chroot, string serverPath)

{

if (string.IsNullOrEmpty(chroot)) return serverPath;

return string.Compare(serverPath, chroot, StringComparison.Ordinal) == 0 ? "/" : serverPath.Substring(chroot.Length);

}

ICP备案号:苏ICP备14035786号-1 苏公网安备 32050502001014号