How to convert httppostedfilebase to String array
Asked Answered
E

2

12
    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?

Etsukoetta answered 24/3, 2015 at 7:24 Comment(0)
K
18

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());
    }
}
Kaiak answered 24/3, 2015 at 8:24 Comment(0)
E
5

From another thread addressing the same issue, this answer helped me get the posted file to a string -

https://mcmap.net/q/280742/-asp-net-mvc-read-file-from-httppostedfilebase-without-save

To quote,

string result = string.Empty;

using (BinaryReader b = new BinaryReader(file.InputStream))
{
  byte[] binData = b.ReadBytes(file.ContentLength);
  result = System.Text.Encoding.UTF8.GetString(binData);
}

Splitting the string into an array -

string[] csvData = new string[] { };

csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Execution answered 10/6, 2017 at 7:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.