[英]How do I download a CSV file to a string from an https URL?
The code that I have listed here works when I ReadAllText from a local file.当我从本地文件中读取所有文本时,我在此处列出的代码有效。 What I need to be able to do is replace the path "C:\LocalFiles\myFile.csv" with " https://mySite.blah/myFile.csv ".
我需要做的是将路径“C:\LocalFiles\myFile.csv”替换为“ https://mySite.blah/myFile.csv ”。
I have tried several methods, but can't seem to be able to get the csv file loaded into a string variable.我尝试了几种方法,但似乎无法将 csv 文件加载到字符串变量中。 If I could just do that, then the code would work for me.
如果我能做到这一点,那么代码就会为我工作。
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();
If I simply replace the path, I get an error message that says that the path is invalid.如果我只是替换路径,我会收到一条错误消息,指出路径无效。
You need to get the string using a web request:您需要使用 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();
}
or using a Webclient:或使用网络客户端:
WebClient wc = new WebClient();
string data = wc.DownloadString("https://mySite.blah/myFile.csv");
Then pass data
into your reader instead of using the System.IO.File.ReadAllText(@"C:\LocalFiles\myFile.csv");
然后将
data
传递到您的阅读器,而不是使用System.IO.File.ReadAllText(@"C:\LocalFiles\myFile.csv");
Both of the above examples assume that the file is publicly accessible at that url without authentication or specific header values.上述两个示例都假定该文件可在 url 处公开访问,无需身份验证或特定 header 值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.