用于验证基于Windows的文件路径(包括UNC路径)的正则表达式

时间:2012-08-02 12:06:57

标签: regex path

我想验证文件名及其完整路径。我尝试了下面的某些正则表达式,但没有一个能正常工作。

^(?:[\w]\:|\\)(\\[a-z_\-\s0-9\.]+)+\.(txt|gif|pdf|doc|docx|xls|xlsx)$
and
^(([a-zA-Z]\:)|(\\))(\\{1}|((\\{1})[^\\]([^/:*?<>""|]*))+)$
etc...

我的要求如下: 让我们说如果文件名是“c:\ Demo.txt”那么它应该检查每个可能性,如不应该包含双斜杠(c:\\Demo\\demo.text)没有像(c::\Demo\demo.text)那样的额外冒号。应该接受UNC文件,如(\\staging\servers)和其他验证。请帮忙。我真的被困在这里了。

2 个答案:

答案 0 :(得分:2)

为什么不使用File类? 一直使用它!

File f = null;
string sPathToTest = "C:\Test.txt";
try{
f = new File(sPathToTest );
}catch(Exception e){
   Console.WriteLine(string.Format("The file \"{0}\" is not a valid path, Error : {1}.", sPathToTest , e.Message);
}

MSDN:http://msdn.microsoft.com/en-gb/library/system.io.file%28v=vs.80%29.aspx

也许您只是在寻找File.Exists(http://msdn.microsoft.com/en-gb/library/system.io.file.exists%28v=vs.80%29.aspx

另请查看Path类(http://msdn.microsoft.com/en-us/library/system.io.path.aspx

GetAbsolutePath可能是获得您想要的一种方式! (http://msdn.microsoft.com/en-us/library/system.io.path.getfullpath.aspx

string sPathToTest = "C:\Test.txt";
string sAbsolutePath = "";
try{
   sAbsolutePath = Path.GetAbsolutePath(sPathToTest);
   if(!string.IsNullOrEmpty(sAbsolutePath)){
     Console.WriteLine("Path valid");
   }else{
     Console.WriteLine("Bad path");
   }
}catch(Exception e){
   Console.WriteLine(string.Format("The file \"{0}\" is not a valid path, Error : {1}.", sPathToTest , e.Message);

}

答案 1 :(得分:0)

如果您只对文件名部分感兴趣(而不是整个路径,因为您通过上传获取文件),那么您可以尝试这样的事情:

string uploadedName =  @"XX:\dem<<-***\demo.txt";

int pos = uploadedName.LastIndexOf("\\");
if(pos > -1)
    uploadedName = uploadedName.Substring(pos+1);

var c = Path.GetInvalidFileNameChars();
if(uploadedName.IndexOfAny(c) != -1)
     Console.WriteLine("Invalid name");
else
     Console.WriteLine("Acceptable name");

这将避免使用Exceptions作为驱动代码逻辑的方法。

相关问题