How to validate if the string has a filename along with the path review below.
I am looking for a regex that validates if the string has a filename along with the path. review below.
Example:
C:\temp\ Incorrect because of ";" Incorrect
C:\temp\example.txt Correct
Loading

Hemant SrivastavaRank #581 · 4.2K reputationPosted Aug 5, 2013, 1:27 PM EDT
^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$
Hemant SrivastavaRank #581 · 4.2K reputationPosted Aug 5, 2013, 1:29 PM EDT
\\test\test$\TEST.xls
\\server\share\folder\myfile.txt
\\server\share\myfile.txt
\\123.123.123.123\share\folder\myfile.txt
c:\folder\myfile.txt
c:\folder\myfileWithoutExtension
David SmithRank #999 · 2K reputationPosted Aug 5, 2013, 3:28 PM EDT
I am using this in the order below in code, It seems the first regex works for both the filename and the filepath. I never make to the seconds regex if set the string to the data below. review
Example
string filepath = "C:\temp\"
string filename = "C:\temp\"
private const string regex1 = @"^(?:[A-Za-z]\:|\\)(\\[a-zA-Z_\-\s0-9\.]+)+(\.\w+)?$";
private const string regex2 = @"^(?:[a-zA-Z]\:|\\\\[\w\.]+\\[\w.$]+)\\(?:[\w]+\\)*\w([\w.])+$";
Regex r= new Regex(regex1 );
if (!r.IsMatch(filename))
{
throw new ArgumentNullException("filepath");
}
Regex r= new Regex(regex2);
if (!r.IsMatch(filename))
{
throw new ArgumentNullException("filename");
}