Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular Expression for validating Windows-based file paths including UNC paths

Tags:

regex

path

I wanted to validate a file name along with its full path. I tried certain Regular Expressions as below but none of them worked correctly.

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

My requirement is as mentioned below: Lets say if the file name is "c:\Demo.txt" then it should check every possibilites like no double slash should be included(c:\\Demo\\demo.text) no extra colon like(c::\Demo\demo.text). Should accept UNC files like(\\staging\servers) and others validation as well. Please help. I am really stuck here.

like image 210
Running Rabbit Avatar asked Nov 04 '22 19:11

Running Rabbit


1 Answers

Why are you not using the File class ? Always use it !

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

Maybe you're just looking for File.Exists ( http://msdn.microsoft.com/en-gb/library/system.io.file.exists%28v=vs.80%29.aspx )

Also take a look to the Path class ( http://msdn.microsoft.com/en-us/library/system.io.path.aspx )

The GetAbsolutePath could be one way to get what you want! ( 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);

}
like image 125
ykatchou Avatar answered Nov 14 '22 02:11

ykatchou