Search code examples
c#asp.nethttprequesthttpfilecollection

HTTPRequest.Files.Count Never Equals Zero


I have a form on an HTML page that a user needs to use to upload a file which posts to an ASPX page. In the code behind, I want to test if a file has actually been loaded.

if (Request.Files.Count > 0)
{
    DoStuff(Request.Files[0]);
}
else
{
    throw new Exception("A CSV file must be selected for upload.");
}

I am never getting to the else. Is this just how ASP.NET operates? If I have a input element of type file, is it always going to upload a "file" even if one is not selected?

What's the proper way to do this? Maybe this?

if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
    DoStuff(Request.Files[0]);
}
else
{
    throw new Exception("A CSV file must be selected for upload.");
}

Solution

  • Maybe just this will do:

    if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
    {
        DoStuff(Request.Files[0]);
    }
    else
    {
        throw new Exception("A CSV file must be selected for upload.");
    }