C# 判断文件夹格式是否合法(含中文):无需正则表达式
在 C# 中判断自定义文件夹格式是否合法,可以使用中文,可以通过以下方法实现:
-
使用
System.IO命名空间下的Directory类中的Exists方法判断文件夹是否存在。 -
使用
System.IO命名空间下的Path类中的GetInvalidPathChars方法获取非法字符数组,然后遍历文件夹名称中的字符是否在非法字符数组中存在,如果存在则判定为非法。
示例代码如下:
using System.IO;
public bool CheckFolderName(string folderName)
{
char[] invalidChars = Path.GetInvalidPathChars();
foreach (char c in folderName)
{
if (Array.IndexOf(invalidChars, c) >= 0)
{
return false;
}
}
return Directory.Exists(folderName);
}
以上代码可以判断文件夹名称中是否包含非法字符,并且判断文件夹是否存在。如果返回值为 true 则表示文件夹格式符合要求,反之则不符合要求。
原文地址: https://www.cveoy.top/t/topic/lpRT 著作权归作者所有。请勿转载和采集!