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

C#.NetFile

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

Check against GetInvalidFileNameChars():

var isValid = !string.IsNullOrEmpty(fileName) &&
              fileName.IndexOfAny(Path.GetInvalidFileNameChars()) < 0 &&
              !File.Exists(Path.Combine(sourceFolder, fileName));

Solution 3 - C#

If the file is going to be created, You should use a file dialog to specify the directory path. There's a short list of illegal characters for file names.

The only truly reliable way to tell if a file name is acceptable is to try it. Permissions is a morass.

Solution 4 - C#

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;
}

Should take care of everything but reserved names, permissions, and length restrictions. This accepts both relative and absolute filenames.

Solution 5 - C#

This is just an idea. One should populate the exception list:

public static bool IsValidFilename(string filename)
{
    try
    {
        File.OpenRead(filename).Close();
    }
    catch (ArgumentException) { return false; }
    catch (Exception) { }
    return true;
}

Solution 6 - C#

For first part(Valid Filename), I use all ways and a temporary file creation to check if a file can be named as expected or throws an exception.
In some cases creating a file will not raise an exception until trying to delete it(eg: CON).
I also usa removePath arg to dictate it that file is just the name of file without its path.

using System.IO;
using System.Text;

private static readonly byte[] TestFileBytes = Encoding.ASCII.GetBytes(@"X");

public bool IsFileNameValid(string file, bool removePath = false)
{
    try
    {
        if (string.IsNullOrEmpty(file))
            return false;

        string fileNamePart = removePath ? Path.GetFileName(file) : file;
        if (fileNamePart.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
            return false;

        string fileName = Path.Combine(Path.GetTempPath(), fileNamePart);
        using FileStream fileStream = File.Create(fileName);
        {
            fileStream.Write(TestFileBytes, 0, TestFileBytes.Length);
        }

        File.Delete(fileName);
        return true;
    }
    catch
    {
        return false;
    }
}

> If there is any denial of access to temp folder use a custom folder for creating test file.

> This method will result false for . or .. or ... r any sequence of dot-only names in Windows, and also you can't create them manually, but those are not actually invalid names! those are uncreatable names for file or something like that ;).

And for next part(Not exists) just use: !File.Exists(yourFileNameWithPath).

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRoflcoptrExceptionView Question on Stackoverflow
Solution 1 - C#SLaksView Answer on Stackoverflow
Solution 2 - C#Phil HuntView Answer on Stackoverflow
Solution 3 - C#ddyerView Answer on Stackoverflow
Solution 4 - C#Duke NukemView Answer on Stackoverflow
Solution 5 - C#BitterblueView Answer on Stackoverflow
Solution 6 - C#shA.tView Answer on Stackoverflow