Ric*_*ide 7 asp.net-mvc file filestream
在保存上传的csv文件之前,我想检查它是否会解析.当我只是保存文件时一切都很好,现在我正在读它,保存的文件是空白的.
这是我的行动方法
[HttpPost]
public ActionResult Import(HttpPostedFileBase file)
{
// Check parse went ok
using (var fileStream = file.InputStream)
{
if (!MemberFileParsingService.CheckFileWillParse(fileStream))
{
ViewBag.Message = "There was a problem with the file";
return View();
}
}
// Save file so we can work on it in next action
file.SaveAs(Server.MapPath(fileName));
return RedirectToAction("ImportMatch", new { club = ActiveClub.Url });
}
Run Code Online (Sandbox Code Playgroud)
这是我的方法,检查文件解析是否正常.它使用CsvReader来读取整个文件以检查没有错误.当涉及到文件的坏位时,CsvReader会抛出异常.
public static bool CheckFileWillParse(Stream fileStream)
{
try
{
using (var reader = new StreamReader(fileStream))
{
using (CsvReader csv = new CsvReader(reader, false))
{
while (csv.ReadNextRecord()) { }
}
}
}
catch(Exception)
{
return false;
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
我想这可能是因为它试图使用现在位于文件末尾的相同流来编写文件.我不知道如何重置流.我希望我所有的使用声明都能解决这个问题.
那么如何重置流,或者只是一个红鲱鱼?
更新:通过CheckFileWillParse发现流的长度重置为零,所以看起来重置流只是一个红色的鲱鱼,流实际上是以某种方式被消隐.
您必须回放流(如果可能).读取后,当前位置位于流的末尾,这就是保存文件时文件为空的原因.
您可以使用Seek函数或Position属性来执行此操作(将其设置为0).但并非所有流类型都支持此功能.
如果流类型不支持它,您可能需要先将文件写入磁盘,然后针对它运行测试.