Gav*_*vin 8 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
}
Run Code Online (Sandbox Code Playgroud)
我知道将httppostedfilebase转换为String数组的常用方法,它首先将文件存储在服务器中,然后从服务器读取数据.无论如何直接从httppostedfilebase获取字符串数组而不将文件存储到服务器中?
teo*_*kot 13
那么你可以逐行读取你的文件,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());
}
}
Run Code Online (Sandbox Code Playgroud)
从解决同一问题的另一个线程中,这个答案帮助我将发布的文件转换为字符串 -
去引用,
string result = string.Empty;
using (BinaryReader b = new BinaryReader(file.InputStream))
{
byte[] binData = b.ReadBytes(file.ContentLength);
result = System.Text.Encoding.UTF8.GetString(binData);
}
Run Code Online (Sandbox Code Playgroud)
将字符串拆分为数组 -
string[] csvData = new string[] { };
csvData = result.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8510 次 |
最近记录: |