Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 863
Gavin Avatar asked Mar 24 '15 07:03

Gavin


2 Answers

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());
    }
}
like image 94
teo van kot Avatar answered Nov 09 '22 04:11

teo van kot


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

https://stackoverflow.com/a/40304761/5333178

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);
like image 24
Abhishek Poojary Avatar answered Nov 09 '22 04:11

Abhishek Poojary