0

I have the following C# code:

string File = "../images/main/profile-icon.png";
if (Request.ContentLength != 0)
{
    int Size = Request.Files[0].ContentLength / 1024;
    if (Size <= 512)
    {

        string LocalFile = Request.Files[0].FileName;
        int dot = LocalFile.LastIndexOf('.');
        string FileType = LocalFile.Substring(dot + 1);
        if (FileType == "gif" || FileType == "jpg" || FileType == "png" || FileType == "GIF" || FileType == "JPG" || FileType == "PNG")
        {
            int LastIndex = LocalFile.LastIndexOf(@"\") + 1;
             File = LocalFile.Substring(LastIndex, LocalFile.Length - LastIndex);
            File = DateTime.Today.ToString();
            string Path = Server.MapPath(" ../images/profiles") + "..\\" + File;
            Request.Files[0].SaveAs(Path);
        }
    }
    else
    {
        Response.Write("The file is too big !");
    }
}
else
{
    Response.Write("Unknown Error !");
}

The problem is that in the third code line I get the following error:

Index was out of range. Must be non-negative and less than the size of the collection.

this is the form HTML source:

<form name="Register" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile('Register');">
    <p>
       photo:
        <input type="file" name="File" style="margin-right:10px;" />
    </p>
</form>

My question is why and how can I fix this?

Wish for help, thanks!

7
  • In this line " int Size = Request.Files[0].ContentLength / 1024;" Commented Jun 4, 2013 at 14:41
  • you seem to be testing Request.ContentLength != 0 and then accessing Request.Files[0] I guess it is the issue Commented Jun 4, 2013 at 14:42
  • Check the number of items in Files. Commented Jun 4, 2013 at 14:42
  • In the file that I test the ConentLength was about 350 Commented Jun 4, 2013 at 14:43
  • 2
    Why don't you test Request.Files.Count ? Commented Jun 4, 2013 at 14:44

1 Answer 1

6

It appears that the Files array has no elements, maybe you can add a check:

if(Request.Files.Count > 0)
{
   // continue here ...
}

This probably means that you're not uploading the file correctly and it's missing from the request.

EDIT: Try to set the enctype="multipart/form-data" in your form tag. So it will become something like:

<form name="Register" runat="server" style="margin-top: 15px;" onsubmit="return validateProfile('Register');" enctype="multipart/form-data">
Sign up to request clarification or add additional context in comments.

2 Comments

Hi, thank you for the answer, but now it does not 'enter' into the condition although there is a file in the form, why?
It means you're not uploading it correctly. Maybe you can show us your markup.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.