We have answer of your question!

100% solved queries, no empty question

Question: Error when trying upload file aspx / C#



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;
        Response.Write("The file is too big !");
    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');">
        <input type="file" name="File" style="margin-right:10px;" />

My question is why and how can I fix this?

Wish for help, thanks!

Question author Nave-tseva | Source




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">
Answer author Dimitar-dimitrov


Tickanswer.com is providing the only single recommended solution of the question Error when trying upload file aspx / C# under the categories i.e c# , asp.net , file , file-upload , . Our team of experts filter the best solution for you.

Related Search Queries:

file upload without fileupload control in asp net c# ,

You may also add your answer!