Asp.net-Mvc

如何將 httppostedfilebase 轉換為字元串數組

  • June 10, 2017
   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());
   }
}

從另一個解決相同問題的執行緒中,這個答案幫助我將發布的文件轉換為字元串 -

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

引用自:https://stackoverflow.com/questions/29227000