Regular expression for checking Windows file paths, including UNC paths

I wanted to check the file name along with its full path. I tried some regular expressions as shown 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 requirements are given below: Suppose that if the file name is "c: \ Demo.txt", then it should check all the possibilities, for example, if you do not include a double slash ( c:\\Demo\\demo.text), there is no additional colon ( c::\Demo\demo.text). You should accept UNC files such as ( \\staging\servers) and other checks. Please help. I am really stuck here.

+5
source share
2 answers

Why aren't you 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

, 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);

}
+2

( , ), - :

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");

.

0

All Articles