如何从https URL下载CSV文件到字符串?

pkbketx9  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(108)

当我从本地文件中读取AllText时,我在这里列出的代码可以工作。我需要能够做的是将路径“C:\LocalFiles\myFile.csv”替换为“https://mySite.blah/myFile.csv“。
我尝试了几种方法,但似乎无法将csv文件加载到字符串变量中。如果我能做到这一点,那么代码将为我工作。

var csv = System.IO.File.ReadAllText(@"C:\LocalFiles\myFile.csv");

StringBuilder sb = new StringBuilder();
using (var p = ChoCSVReader.LoadText(csv).WithFirstLineHeader())
{
    p.Configuration.NullValue = null;

    if (p.Configuration.CSVRecordFieldConfigurations.IsNullOrEmpty())
    {
        p.Configuration.NullValue = null;
    }

    // ChoIgnoreFieldValueMode.DBNull = ChoIgnoreFieldValueMode.Empty();
    using (var w = new ChoJSONWriter(sb))
        w.Write(p);
}
string fullJson = sb.ToString();

字符串
如果我只是简单地替换路径,我会得到一条错误消息,指出路径无效。

r55awzrz

r55awzrz1#

您需要使用Web请求获取字符串:

string urlAddress = "https://mySite.blah/myFile.csv";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
    Stream receiveStream = response.GetResponseStream();
    StreamReader readStream = null;
    if (response.CharacterSet == null)
    {
        readStream = new StreamReader(receiveStream);
    }
    else
    {
        readStream = new StreamReader(receiveStream,
        Encoding.GetEncoding(response.CharacterSet));
    }

    string data = readStream.ReadToEnd();
    response.Close();
    readStream.Close();
}

字符串
或者使用Webclient:

WebClient wc = new WebClient();
string data = wc.DownloadString("https://mySite.blah/myFile.csv");


然后将data传递到阅读器中,而不是使用System.IO.File.ReadAllText(@"C:\LocalFiles\myFile.csv");
上面的两个例子都假设文件可以在该url上公开访问,而不需要身份验证或特定的头值。

5m1hhzi4

5m1hhzi42#

替换此行
var csv = System.IO.File.ReadAllText(@"C:\LocalFiles\myFile.csv");

string result = client.GetStringAsync("https://mySite.blah/myFile.csv").Result;

var textFromFile = (new WebClient()).DownloadString("https://mySite.blah/myFile.csv");
还有很多其他方法可以做到这一点。谷歌一下就知道了。

相关问题