【发布时间】:2021-10-24 03:53:14
【问题描述】:
我尝试使用以下代码解析正在上传的 CSV 文件:
private Dictionary<string, string[]> LoadData(IFormFile file)
{
// Verify that the user selected a file
if (file != null && file.Length > 0)
{
string wwwPath = this.environment.WebRootPath;
// string contentPath = this.environment.ContentRootPath;
string path = Path.Combine(wwwPath, "WeeklySchedules");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.GetFileName(file.FileName);
using (FileStream stream = new FileStream(Path.Combine(path, fileName), FileMode.Create))
{
file.CopyTo(stream);
// System.Threading.Thread.Sleep(1000);
using (TextFieldParser parser = new TextFieldParser(Path.Combine(path, fileName)))
{
parser.TextFieldType = FieldType.Delimited;
parser.SetDelimiters(",");
Dictionary<string, string[]> parsedData = new Dictionary<string, string[]>();
while (!parser.EndOfData)
{
// Process row
string[] fields = parser.ReadFields();
int count = 0;
if (count++ == 0)
{
continue;
}
var pickup = fields[0];
var pickupDate = fields[1];
var dropoff = fields[2];
var dropoffDate = fields[3];
var driver = fields[7];
var pickupTime = DateTime.Parse(pickupDate).ToLongTimeString();
// string[] data =
}
}
}
}
return null;
}
您会注意到,我将上传流的路径传递给解析器,而不是流本身。我尝试在流中传递,但这也不起作用。当我签入 wwwroot/WeeklySchedules 时,该文件就在那里。但是当解析器到达它时,它返回为空。我什至输入了一个 Sleep() 来查看我是否过早地点击了文件。但这并没有什么不同。
我在原始流中遇到了一些奇怪的错误,但文件已写入,这让我感到困惑。
错误是:
stream.ReadTimeout = 'stream.ReadTimeout' 抛出“System.InvalidOperationException”类型的异常
stream.WriteTimeout = 'stream.WriteTimeout' 引发了“System.InvalidOperationException”类型的异常
我已经阅读了一堆关于加载/解析 CSV 文件的技术的博客文章和 SO 问题,但没有一个表明这是一个问题。
有人有什么想法吗?
【问题讨论】:
标签: c# asp.net-core-mvc text-parsing