Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to check if an arbitrary String is a valid filename

Tags:

c#

.net

file

In my application the user can enter a filename. Before processing I'd like to check if the input String is a valid filename on Windows Vista.

Whats the easiest way to do that?

By valid I'm reffering to legal and non-existing

like image 396
RoflcoptrException Avatar asked Jan 10 '11 19:01

RoflcoptrException


People also ask

How do you check if a string is a valid file name Java?

We can use the String. contains() method to check if the given String holds any of the forbidden characters.

What makes a file name valid?

File names can contain any of the following characters: A-Z, a-z, 0-9, underscore, hyphen, space, period, parenthesis, curly braces, square brackets, tilde, exclamation point, comma, semicolon, apostrophe, at sign, number sign, dollar sign, percent sign, plus sign, and equal sign.


2 Answers

Check whether filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 and !File.Exists(Path.Combine(someFolder, filename))

like image 160
SLaks Avatar answered Sep 17 '22 17:09

SLaks


Check against GetInvalidFileNameChars():

var isValid = !string.IsNullOrEmpty(fileName) &&               fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&               !File.Exists(Path.Combine(sourceFolder, fileName)); 
like image 26
Phil Hunt Avatar answered Sep 21 '22 17:09

Phil Hunt