Solved

Test if the filename is legal

Posted on 2007-11-20
2
540 Views
Last Modified: 2013-11-07
I am building a filename on some text fields so if the user put in the wrong signs the filename will be illegal.

Is there a build in function in C# to test if the filename is legal?
If someone have a few lines of code that can do the same it will be helpfull as well.

/Peter
0
Comment
Question by:PeterSvendsen
  • 2
2 Comments
 
LVL 7

Expert Comment

by:bungHoc
ID: 20318637
- Get all invalid path characters
- Use Regular Expressions to check if file name is legit


char[] invalidPathChars = System.IO.Path.GetInvalidPathChars();
string invalid = Regex.Escape (new string (invalidPathChars));
string validFileName = Regex.Replace (input, "[" + invalid + "]", "");

0
 
LVL 7

Accepted Solution

by:
bungHoc earned 500 total points
ID: 20318660
This should work better:
private bool isValidFilename(string filename)
{
  char[] invalidFileChars = Path.GetInvalidFileNameChars();
  return (filename.IndexOfAny(invalidFileChars) < 0);
}
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
This article shows how to deploy dynamic backgrounds to computers depending on the aspect ratio of display
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
Although Jacob Bernoulli (1654-1705) has been credited as the creator of "Binomial Distribution Table", Gottfried Leibniz (1646-1716) did his dissertation on the subject in 1666; Leibniz you may recall is the co-inventor of "Calculus" and beat Isaac…

803 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question