【问题标题】:Download CSV file using HttpClient and Process with CsvHelper onfly使用 HttpClient 下载 CSV 文件并使用 CsvHelper onfly 处理
【发布时间】:2020-08-05 10:45:16
【问题描述】:

我正在尝试使用 HttpClient 下载 csv 文件并使用 CsvHelper 库进行处理

string url = "https://www.nseindia.com/api/allIndices?csv=true";
string useragent = @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36";

var httpclient = new HttpClient();

var request = new HttpRequestMessage(HttpMethod.Get, url);
var sendtask = httpclient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
var response = sendtask.Result.EnsureSuccessStatusCode();
var httpStream = await response.Content.ReadAsStreamAsync();
StreamReader streamreader = new StreamReader(httpStream);

CsvReader futureoptionsreader = new CsvReader(streamreader, CultureInfo.CreateSpecificCulture("en-US"));
futureoptionsreader.Configuration.RegisterClassMap<MappingNSEIndexes>();
var list = futureoptionsreader.GetRecords<RawNSEIndexes>();
var number = list.Count();

以错误的数据错误结束

CsvHelper.BadDataException: You can ignore bad data by setting BadDataFound to null.
   at CsvHelper.CsvParser.Read()
   at CsvHelper.CsvReader.Read()
   at CsvHelper.CsvReader.GetRecords[T]()+MoveNext()
   at System.Linq.Enumerable.Count[TSource](IEnumerable`1 source)
   at MIS.Equity.API.Controllers.BooksController.GetCompaniesAsync() in C:\Users\Ramesh\source\repos\MIS_Main\MarkertInfoSystem\MIS.Equity.API\Controllers\BooksController.cs:line 66
   at lambda_method(Closure , Object )
   at Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable.Awaiter.GetResult()
   at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.AwaitableResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)

这种方法正确吗?提前致谢

【问题讨论】:

  • 你有2个问题,下载文件,处理csv,你是否将csv数据保存到文件并检查它实际上是一个csv?如果是,那么你只有一个问题……但我们无法分辨它是什么,只有你
  • 有。 很多 的问题与此代码,但错误抱怨 数据,而不是代码。你检查过文件包含的内容吗?标题相当……奇怪。
  • @TheGeneral - 我不是在尝试将 csv 文件下载到我的系统,而是在尝试加载到 CsvHepler。
  • 不是一个大错误,但您在获得响应时阻塞了当前线程,修复:var response = (await sendtask).EnsureSuccessStatusCode()。而且您完全忽略了IDisposables,如果您想在每个应用程序生命周期中多次运行该代码,那真的很糟糕。关于 BadData,请参考this answer
  • 好像是CSV文件的结构有问题。标题(带有字段名)在每个字段名之后包含一个换行符...

标签: c# csvhelper


【解决方案1】:

所以,您发布的代码有点过时...我无法编译它,所以我重新编写了它以遵循使用 HttpClient 时的常见模式:

var url = "https://www.nseindia.com/api/allIndices?csv=true";

using (var msg = new HttpRequestMessage(HttpMethod.Get, new Uri(url)))
{
    msg.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));
    using (var resp = await _client.SendAsync(msg))
    {
        resp.EnsureSuccessStatusCode();

        using (var s = await resp.Content.ReadAsStreamAsync())
        using (var sr = new StreamReader(s))
        using (var futureoptionsreader = new CsvReader(sr, CultureInfo.CurrentCulture))
        {
            futureoptionsreader.Configuration.RegisterClassMap<MappingNSEIndexes>();
            var list = futureoptionsreader.GetRecords<RawNSEIndexes>();
            var number = list.Count();
        }
    }
}

请记住,除非您添加 Headers.Accept 行,否则服务器不会返回任何数据。

主要问题之一是这一行:

var response = sendtask.Result.EnsureSuccessStatusCode();
var httpStream = await response.Content.ReadAsStreamAsync();

这甚至无法编译——EnsureSuccessStatusCode 返回void。因此,我假设您在尝试排除故障后修改并粘贴代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-02
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    相关资源
    最近更新 更多