Search code examples
c#htmlfile-type

Which FIle Form Field For C# Request.Files[n].FileName


If I have a HTML form with multiple input file fields (where 'N' is a unique number);

<input type="file" name="inputFileN"> 

Then in the C# code;

string inFile = System.IO.Path.GetFileName(Request.Files[M].FileName)

Is there any way I can ascertain the value of 'M' from the Request data so I can match against a specific HTML input file-type field ?

This is in a situation where the end-user can update the fields on an edit form and it works ok for for all field types apart from the file-type field.


Solution

  • All of the necessary data is in HttpContext.Request.Files; specifically, in HttpContext.Request.Files.AllKeys:

    //HttpContext is a member of `System.Web.Mvc.Controller`,
    //accessible in controllers that inherit from `System.Web.Mvc.Controller`.
    System.Web.HttpFileCollectionBase files = HttpContext.Request.Files;
    string[] fieldNames = files.AllKeys;
    for (int i = 0; i < fieldNames.Length; ++i)
    {
        string field = fieldNames[i]; //The 'name' attribute of the html form
        System.Web.HttpPostedFileBase file = files[i];
        string fileName = files[i].FileName; //The path to the file on the client computer
        int len = files[i].ContentLength; //The length of the file
        string type = files[i].ContentType; //The file's MIME type
        System.IO.Stream stream = files[i].InputStream; //The actual file data
    }