M H
M H

Reputation: 2183

How do you properly write a foreach loop to upload multiple files in asp.net C#

I have seen this style demo'ed on many sites as a way to upload multiple files in asp.net, but I cannot get it to work. If I select 6 files, it only ends up saving one file, but the label shows 6 filenames of the same name. WHen I debug, it shows each file name on each loop like I would want it to. Why is it not working?

Also, I have an update panel on the page if that matters.

I am using an asp.net upload control with multiple uploads turned on. I know the paths are correct because it works perfect when I upload only one file.

string Path = Request.Url.AbsolutePath;
string ProperPath = Path.Replace(@"Pages/InsertVideo.aspx", @"TrainingMaterial/Video/");

if (FileUpload1.HasFiles) { 
    //SaveFile(FileUpload1.PostedFile);

    foreach (HttpPostedFile File in FileUpload1.PostedFiles)
    {
        FileUpload1.SaveAs(System.IO.Path.Combine(Server.MapPath(ProperPath), FileUpload1.FileName));
        lblFilesUploaded1.Text += String.Format("{0}<br />", FileUpload1.FileName);
    }
}

I also tried this technique with same results as above. Any advice? I am thinking it has to do with my SaveAs string.

foreach (string key in Request.Files)
{
    HttpPostedFile file = Request.Files[key];
    if (file.ContentLength != 0)
    {
        file.SaveAs(System.IO.Path.Combine(Server.MapPath(ProperPath), FileUpload1.FileName));
    }
}

Upvotes: 1

Views: 7168

Answers (1)

Peter Kiss
Peter Kiss

Reputation: 9319

This shoud do the trick:

if (FileUpload1.HasFiles)
{
    foreach (var file in FileUpload1.PostedFiles)
    {
        file.SaveAs(Path.Combine(Server.MapPath(ProperPath), file.FileName));
        lblFilesUploaded1.Text += String.Format("{0}<br />", file.FileName);
    }
}

In your solution you are referring in the foreach always the FileUpload control not the current uploaded file.

Upvotes: 5

Related Questions