The easiest way to check if an arbitrary String is a valid file name

In my application, the user can enter a file name. Before processing, I would like to check if the input string is the correct file name in Windows Vista.

The easiest way to do this?

In fact, I return to legal and nonexistent

+51
c # file
Jan 10 '11 at 19:07
source share
4 answers

Make sure filename.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0 and !File.Exists(Path.Combine(someFolder, filename))

+88
Jan 10 '11 at 19:10
source share

Refuse GetInvalidFileNameChars() :

 var isValid = !string.IsNullOrEmpty(fileName) && fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 && !File.Exists(Path.Combine(sourceFolder, fileName)); 
+25
Jan 10 '11 at 19:11
source share

If a file is created, you must use the file dialog to specify the directory path. There is a short list of invalid characters for file names.

The only reliable way to find out if a file name is valid is to try it. access rights is a swamp.

+12
Jan 10 '11 at 19:15
source share

I use this:

 public static bool IsValidFileName(string name) { if(string.IsNullOrWhiteSpace(name)) return false; if(name.Length > 1 && name[1] == ':') { if(name.Length < 4 || name.ToLower()[0] < 'a' || name.ToLower()[0] > 'z' || name[2] != '\\') return false; name = name.Substring(3); } if(name.StartsWith("\\\\")) name = name.Substring(1); if(name.EndsWith("\\") || !name.Trim().Equals(name) || name.Contains("\\\\") || name.IndexOfAny(Path.GetInvalidFileNameChars().Where(x=>x!='\\').ToArray()) >= 0) return false; return true; } 

You should take care of everything except reserved names, permissions, and length restrictions. This accepts both relative and absolute file names.

0
Oct. 16 '17 at 4:06 on
source share



All Articles