asp.net-mvchttppostedfilebase

How to convert httppostedfilebase to String array


    public ActionResult Import(HttpPostedFileBase currencyConversionsFile)
    {

        string filename = "CurrencyConversion Upload_" + DateTime.Now.ToString("dd-MM-yyyy") + ".csv";
        string folderPath = Server.MapPath("~/Files/");

        string filePath = Server.MapPath("~/Files/" + filename);
        currencyConversionsFile.SaveAs(filePath);
        string[] csvData = System.IO.File.ReadAllLines(filePath);

        //the later code isn't show here
        }

I know the usual way to convert httppostedfilebase to String array, which will store the file in the server first, then read the data from the server. Is there anyway to get the string array directly from the httppostedfilebase with out store the file into the server?


Solution

  • Well you can read your file line by line from Stream like this:

    List<string> csvData = new List<string>();
    using (System.IO.StreamReader reader = new System.IO.StreamReader(currencyConversionsFile.InputStream))
    {
        while (!reader.EndOfStream)
        {
            csvData.Add(reader.ReadLine());
        }
    }