Tharwat 发表于 2015-5-27 21:35:09

玩来玩,不需要这个,除非可能不得不每天检查数百万个文件名,从无效的字符中找到最大的char的整数值,如果要这样做,可能会使用uint或任何字符在引擎盖下,但最大值是124。 static int MaxInvaildChar()。
{。
整型最大值 = 0;。
foreach (var invalidFileNameChar in System.IO.Path.GetInvalidFileNameChars())。
{。
int cintv = Convert.ToInt32(invalidFileNameChar);。
如果 (最大>)。
{。
最大值 = cintv;。
}。
}。
返回最大值;。
}。
并使用 bool 数组 类程序。
{。

静态布尔[] 无效 = 新布尔;。

static void Main(string[] args)。
{。

foreach (var invalidFileNameChar in System.IO.Path.GetInvalidFileNameChars())。
{。
invalids = true;。
}。

string s1 = “hjghjhhjghjghjjg”;。
string s2 = “hjghjhhjghjg.mmmjk”;。
string s3 = “h^jghjhhjghjg.mmmjk”;。
string s4 = “hjghjhh。
string s5 = “aaaaajghjhhjgh>jg.mmmjk”;。
string s6 = “ghjhhjgh|jg.mmmjk”;。
string s7 = “goooooodddddddjg.mmmjk”;。

Console.WriteLine(“{0} = {1}”,s1, IsFileNameValid(s1));。
Console.WriteLine(“{0} = {1}”, s2, IsFileNameValid(s2));。
Console.WriteLine(“{0} = {1}”, s3, IsFileNameValid(s3));。
Console.WriteLine(“{0} = {1}”, s4, IsFileNameValid(s4));。
Console.WriteLine(“{0} = {1}”, s5, IsFileNameValid(s5));。
Console.WriteLine(“{0} = {1}”, s6, IsFileNameValid(s6)); 。
Console.WriteLine(“{0} = {1}”, s7, IsFileNameValid(s7));。
Console.Read();。

}。

static bool IsFileNameValid(string fileName)。
{。
for (int i = 0; i 。
{。
如果 (无效[文件名])。
{。
返回 false;。
}。
}。

返回 true;。
}。

}。

MexicanCustard 发表于 2015-5-28 04:45:31

一个非常好的工作。
谢谢大家:Keith Brown,MexicanCustard,Gile和Jeff H写了这些不同的方法。
只是一个问题 Jeff H ,如果在文件名中发现任何无效的 char,在 if 函数内部的 foreach 循环中有一个中断函数来结束循环不是更好?
谢谢Mat(e)的问候。
我对我离开C#到现在为止所花费的时间感到遗憾,尽管在我开始了解 VS.net 和AutoCAD之间的机制之前,我每天都有很多令人讨厌的消息和 VS.net 错误。
问候。

gile 发表于 2015-5-28 09:26:17

您可以将中断替换为 return 语句,因为它返回值并停止循环。

Jeff_M 发表于 2015-5-28 11:37:11


减少代码数量是一个非常好的主意。 尽管我最后的回答是要求您将中断函数作为我的函数包含在您的函数中,如果这当然被认为是正确的。
谢谢。

Tharwat 发表于 2015-5-28 12:30:38

我只是说 return 语句会打破循环,并使用您的示例来帮助显示它们的相似程度。
页: 1 [2]
查看完整版本: 检查文件名是否有效的方法