【发布时间】:2010-12-16 15:15:01
【问题描述】:
在保存上传的 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 });
}
这是我检查文件是否解析正常的方法。它使用 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;
}
我认为这可能是因为它试图使用现在位于文件末尾的相同流来写入文件。我不知道如何重置流。我希望我所有的 using 语句都能解决这个问题。
那么我怎样才能重置流,或者这只是一个红鲱鱼?
更新:发现流的长度在通过 CheckFileWillParse 后被重置为零,所以看起来重置流只是一个红鲱鱼,流实际上以某种方式被空白。
【问题讨论】:
-
如果从 HttpInputStream 对象构造一个 StreamReader,读取一行以检查标头是否正确,然后重用流(进入第 3 方库),也会发生同样的事情。似乎无法寻找到文件的开头或永远无法取回该行。最烦人!
标签: asp.net-mvc file filestream