C#: Upload a File in .NET MVC and Read the Contents of the File (ex: csv file)

2/8/2015 7:50:05 PM

The following will create an upload form on an MVC .NET view page and create the controller action to read the uploaded file line by line. This code is expecting a csv file.

//form on page
<h1>Upload a CSV File</h1>
@using (Html.BeginForm("uploadfile", "home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div>
        <input type="file" name="files" />
        <input type="submit" value="Upload" />
    </div>
}

//controller and action to handle the upload
[HttpPost]
public ActionResult UploadFile()
{
	//open file
	if (Request.Files.Count == 1)
	{
		//get file
		var postedFile = Request.Files[0];
		if (postedFile.ContentLength > 0)
		{
			//read data from input stream
			using (var csvReader = new System.IO.StreamReader(postedFile.InputStream))
			{
				string inputLine = "";

				//read each line
				while ((inputLine = csvReader.ReadLine()) != null)
				{
					//get lines values
					string[] values = inputLine.Split(new char[] { ',' });
					
					for (int x = 0; x < values.Length; x++)
					{
						//do something with each line and split value
					}
				}

				csvReader.Close();
			}
		}
	}

	return Redirect("/home/uploadfilepage");            
}