Patrick Patrick - 1 year ago 109
C# Question

Downloading/Uploading file, what characters to filter c#

In my application I build a static string when a user uploads or downloads a file. In that string the filename is passed from the frontend in that string. In this way the user could do things like ..\..\another file.file to tamper and get data from other users. Therefor I need to filter the filename that I get to prevent this. What are the characters that need to be filtered to prevent tampering? I now have the double dot and the back and forward slashes. Is there anything else I should take into consideration? Is there maybe a standard way to do this in C#?

Answer Source

I would suggest using Path.GetInvalidFileNameChars:

public static bool IsValidFileName(string fileName)
    return fileName.IndexOfAny(Path.GetInvalidFileNameChars()) == -1;

.. is typically only dangerous when preceded and/or succeeded by a \ or /, both of which are included in the array returned by GetInvalidFileNameChars. By itself, .. is harmless (unless you’re specifically resolving directory paths), and you shouldn’t forbid it since people might want to introduce ellipses in their filename (e.g. The A...Z of Programming.pdf).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download