如何将httppostedfilebase转换为String数组

时间:2015-03-24 07:24:59

标签: asp.net-mvc httppostedfilebase

    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
        }

我知道将httppostedfilebase转换为String数组的常用方法,它首先将文件存储在服务器中,然后从服务器读取数据。无论如何直接从httppostedfilebase获取字符串数组而不将文件存储到服务器中?

2 个答案:

答案 0 :(得分:12)

你可以像Stream一样逐行阅读你的文件:

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

答案 1 :(得分:3)

从解决相同问题的另一个主题,这个答案帮助我将发布的文件转换为字符串 -

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

引用,

string result = string.Empty;

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

将字符串拆分为数组 -

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

csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);