0

I have a string that stores a filename and is used in a SaveFileDialog. I need to ensure that the filename is valid (e.g., contains no slashes) before I assign it to the FileName property of the SaveFileDialog. My question is: Is there a quick way to ensure that the filename is valid before assigning it?

Example:

string fileName = fileNameTextBox.Text;
//Some code here to check validity of fileName
if(fileNameIsValid)
{
  saveFileDialog.FileName = fileName;
}
Joe Sisk
  • 602
  • 1
  • 8
  • 17
  • 8
    Possible duplicate: http://stackoverflow.com/questions/4650462/easiest-way-to-check-if-an-arbitrary-string-is-a-valid-filename – Manoj Awasthi Aug 28 '13 at 17:25
  • One difference the OP should note is that the "duplicate" SO post says existing files are not valid, so you don't need the !File.Exists statement. – Seth Moore Aug 28 '13 at 17:29
  • Thanks, I think it is `fileName.IndexOfAny(Path.GetInvalidFileNameChars()) > 0` – Joe Sisk Aug 28 '13 at 17:30
  • @JoeSisk there's no need to use `GetInvalidFileNameChars`..see my ans – Anirudha Aug 28 '13 at 17:37
  • possible duplicate of [What characters are forbidden in Windows and Linux directory names?](http://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names) – Dour High Arch Mar 19 '15 at 18:44

1 Answers1

6

This question has been asked many times before and, as pointed out many times before, IO.Path.GetInvalidFileNameChars is not adequate.

First, there are many names like PRN and CON that are reserved and not allowed for filenames. There are other names not allowed only at the root folder. Names that end in a period are also not allowed.

Second, there are a variety of length limitations. Read the full list for NTFS here.

Third, you can attach to filesystems that have other limitations. For example, ISO 9660 filenames cannot start with "-" but can contain it.

The only way to find if a filename is invalid is to try to save it and see if it throws an exception.

Community
  • 1
  • 1
Dour High Arch
  • 21,513
  • 29
  • 75
  • 90