C# 判断自定义文件夹格式是否可以使用中文 (无正则表达式)
可以使用以下方法判断自定义文件夹格式是否可以使用中文,不使用正则表达式:
-
使用
System.IO.Directory.Exists()方法判断文件夹路径是否存在,如果不存在则说明不符合格式。 -
使用
System.Text.Encoding.Default.GetBytes()方法将文件夹名称转换为字节数组,然后使用System.Text.Encoding.Default.GetString()方法将字节数组转换为字符串,如果转换后的字符串与原始文件夹名称不同,则说明文件夹名称包含中文字符。 -
使用
System.Text.RegularExpressions.Regex.IsMatch()方法判断文件夹名称是否包含特殊字符,如 \ / : * ? ' < > | 等,如果包含则说明不符合格式。
示例代码如下:
using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string folderPath = @'C:\自定义文件夹\';
if (Directory.Exists(folderPath))
{
byte[] bytes = Encoding.Default.GetBytes(folderPath);
string str = Encoding.Default.GetString(bytes);
if (str != folderPath)
{
Console.WriteLine('文件夹名称包含中文字符');
}
else if (Regex.IsMatch(folderPath, @'[\/:*?'<>|]'))
{
Console.WriteLine('文件夹名称包含特殊字符');
}
else
{
Console.WriteLine('文件夹名称符合格式');
}
}
else
{
Console.WriteLine('文件夹路径不存在');
}
}
}
原文地址: https://www.cveoy.top/t/topic/lpRU 著作权归作者所有。请勿转载和采集!