How to convert httppostedfilebase to String array

Gavin picture Gavin · Mar 24, 2015 · Viewed 11.3k times · Source
    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?

Answer

teo van kot picture teo van kot · Mar 24, 2015

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());
    }
}