Unable to open CSV file from internet using C#

后端 未结 2 1954
栀梦
栀梦 2021-01-27 13:37

I\'m new with C#. I\'ve written code to open a CSV file from my documents on my local machine. It works well and the data parsing works. Trouble is when I change the code to ope

相关标签:
2条回答
  • 2021-01-27 14:21

    Another option is to download data as you're doing, and then wrap it with a MemoryStream:

    WebClient wc = new WebClient();
    byte[] data = wc.DownloadData(
        "http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX");
    
    using (var ms = new MemoryStream(data))
    {
        using (var reader = new StreamReader(ms))
        {
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                // do whatever
            }
        }
    }
    

    The advantage of this over splitting the string is that it uses considerably less memory.

    0 讨论(0)
  • 2021-01-27 14:29

    Your code as pasted would not compile. You can however use the WebClient to download to a string, then split the string into lines:

    string content;
    using(WebClient wc = new WebClient())
    content = wc.DownloadString("http://www.datasource.com/apps/qt/csv/pricehistory.ac?section=yearly_price_download&code=XXX");
    
    foreach(var line in content.Split(new string [] {Environment.NewLine}, StringSplitOptions.None))
    {
        //...
    }
    
    0 讨论(0)
提交回复
热议问题