Reputation: 878
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!
Upvotes: 0
Views: 856
Reputation: 15138
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">
Upvotes: 6