如何将 httppostedfilebase 转换为字符串数组

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
        }

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

你可以像这样从 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());
    }
}

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

引用,

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