1

I use multiple file upload and I want to assign each file name with the global array called img using the foreach how can I do it in asp.net/c#?

string[] img={""};

foreach (string s in Request.Files) {
    HttpPostedFile file = Request.Files[s];
    int fileSizeInBytes = file.ContentLength;
    string fileName = file.FileName;
    string fileExtension = "";

    if (!string.IsNullOrEmpty(fileName)) {
        fileExtension = Path.GetExtension(fileName);
        file.SaveAs(filename);
    }
}

1 Answer 1

2

I would use a List<string> for this purpose:

List<string> img = new List<string>();

foreach (string s in Request.Files)
{
    HttpPostedFile file = Request.Files[s];
    int fileSizeInBytes = file.ContentLength;
    string fileName = file.FileName;
    string fileExtension = "";

    if (!string.IsNullOrEmpty(fileName))
    {
        img.add(fileName);
        fileExtension = Path.GetExtension(fileName);
        file.SaveAs(filename);
    }

Here is a great explanation on why List<T> is almost always better than using an array in C#: https://softwareengineering.stackexchange.com/a/221897

If you give us a little better explanation of what you're trying to accomplish, I could probably improve on this answer.

Sign up to request clarification or add additional context in comments.

4 Comments

thank you, i have a table of items contain img1,img2,img3 and img4 i want to insert the paths of images into those columns img1,img2,etc using linq to sql so i decided to assign each path in array and then assign the array index with the linq
You can get an item by index in a List<T> the same way you can in an array. Just simply use: int myFirstImg = img[0];
thanks, but when int myFirstImg = img[0]; it show this error System.ArgumentOutOfRangeException
That's because you're referencing an index that doesn't exist. Just check that it exists or that img.Count > 0 (or whatever number you need).

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.