判断输入的字符串是否是合法路径,并验证后面的输入是否含有非法字符

#region =方法---判断输入的字符串是否是合法路径,并验证后面的输入是否含有非法字符

尝试过使用正则表达式来判断,但是不是太管用,就就先检测盘符,按照正常的路径“C:\File”的前三位“C:\”判断前三位的输入,后面在判断输入的是否是非法字符,只要不是非法字符,路径就是合法的。

private bool IsCorrectPath(string path)
{
path = path.ToUpper();//转换成大写
string diskStr = "CDEFGHIJK"; //CDEFGHIJK等磁盘,AB大部分不用了
if (path.Length >= 3) //C:\File 长度至少要有4个
{
//1.取第一个,看是否是盘符
string fristChar = path.Substring(0, 1);
if (diskStr.IndexOf(fristChar) >= 0)
{
//2.然后再看后面是不是 :\ 这样的
string lastStr = path.Substring(1, 2);
if (lastStr == ":\\")
{
if (path.Length > 3)
{
string ff = path.Substring(3, path.Length - 3);//去后面的字符
Regex regex = new Regex(@"^[^\/\:\*\?\""\<\>\|\,\;]+$");//非法字符的正则表达式
Match m = regex.Match(ff);
if (m.Success)
{
this.Invoke(new Action(() =>
{
lblMess.Text = "路径合法,请进行下一步";
}));
return true;
}
else
{
this.Invoke(new Action(() =>
{
lblMess.Text = "请勿在文件名中包含\\ / : * ? \" < > |等字符,请重新输入有效文件名!";
}));
return true;
}
}
else
{
this.Invoke(new Action(() =>
{
lblMess.Text = "路径合法,请进行下一步";
}));
return true;
}
}
}
}
this.Invoke(new Action(() =>
{
lblMess.Text = "非法的文件保存路径,请重新选择或输入!";
}));
return false;

}
#endregion

 

posted @ 2020-09-01 17:42  ogre_zl  阅读(1140)  评论(0编辑  收藏  举报