justinpees justinpees -3 years ago 69
ASP.NET (C#) Question

What is the safest and most convenient option to validate file paths of uploaded files for my webform?

I currently have a ValidationExpression on the client-side which (somewhat) restricts the user from uploading anything other than (.txt) files.

^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.txt)$


I was wondering, since this validator restricts some special characters, will I run into trouble if one of my users has the file he wishes to upload inside a folder which has a special character in its name?

Im wondering if there is a better ValidationExpression I can use on the client side to prevent any inconveniences to my users. I am in the process of setting the server-side validation, but I'd still like to have a good client-side validator as well that would allow special characters that are not too risky.

Anyone have a good solution for me?

Answer Source

A quick and simple method of uploading a txt file.

<asp:FileUpload ID="FileUpload1" runat="server" accept=".txt" />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" />
<br />
<asp:Label ID="Label1" runat="server" Text="" ForeColor="Red"></asp:Label>

And then the code behind

protected void Button1_Click(object sender, EventArgs e)
{
    //check if the upload contains a file
    if (FileUpload1.HasFile == false)
    {
        Label1.Text = "No file uploaded.";
        return;
    }

    //check the file extension
    string extension = Path.GetExtension(FileUpload1.FileName);
    if (extension.ToLower() != ".txt")
    {
        Label1.Text = "Not a text file.";
        return;
    }

    //read the content of the text file
    string content = ""; ;
    using (StreamReader sr = new StreamReader(FileUpload1.PostedFile.InputStream))
    {
        content = sr.ReadToEnd();
    }

    //if there is no txt content
    if (string.IsNullOrEmpty(content))
    {
        Label1.Text = "No contents in text file.";
        return;
    }

    Label1.Text = content;

    //save the file
    File.WriteAllText(Server.MapPath("myTextFile.txt"), content);
}

A user could theoretically upload a binary file with a .txt extension. That would result in a lot of unprintable characters in Label1. There are ways you could check even for that. See the following links.

C# - Check if File is Text Based

How can I determine if a file is binary or text in c#?

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