C# 判断自定义文件夹格式是否包含中文 (无正则表达式)
可以使用以下方法判断自定义文件夹格式是否包含中文,无需使用正则表达式:
- 遍历文件夹中所有文件名,使用 foreach 循环
- 对于每个文件名,使用 System.Text.Encoding.Unicode.GetChars() 方法判断是否包含中文。如果包含中文,则说明文件夹格式包含中文。
示例代码:
string folderPath = 'D:\测试文件夹';
bool containsChinese = false;
foreach (string fileName in Directory.GetFiles(folderPath))
{
foreach (char c in System.Text.Encoding.Unicode.GetChars(System.Text.Encoding.Default.GetBytes(fileName)))
{
if (c >= 0x4e00 && c <= 0x9fa5)
{
containsChinese = true;
break;
}
}
if (containsChinese)
{
break;
}
}
if (containsChinese)
{
Console.WriteLine('文件夹格式包含中文');
}
else
{
Console.WriteLine('文件夹格式不包含中文');
}
该代码遍历了指定文件夹下的所有文件名,使用 Unicode 编码判断每个文件名是否包含中文。如果存在中文,则将 containsChinese 设置为 true,跳出循环。最后根据 containsChinese 的值输出判断结果。
原文地址: https://www.cveoy.top/t/topic/lpRX 著作权归作者所有。请勿转载和采集!