C# webclient cannot download text from web

北城以北 提交于 2019-12-24 19:41:15

问题


I am working on a project to get text from this website. But when I tested it in Visual Studio, I've got some error:

Value cannot be null. Parameter name: solutionDirectory

Here is my code:

using System;
using System.Net;

public class Program
{
    public static void Main()
    {
        WebClient client = new WebClient();
        String temp = client.DownloadString("http://www.hkex.com.hk/eng/stat/dmstat/dayrpt/hsio180629.htm");
        Console.Write(temp);
    }
}

回答1:


Please use HttpClient Which is very good Option Compare to webClient And your problem is sounds like your project (vcxproj) file isn't setup properly.

So create New Application Simply and run this Code.

Here you find Actually Difference

 Stream client = Task.Run(()=>new HttpClient().GetAsync("http://www.hkex.com.hk/eng/stat/dmstat/dayrpt/hsio180629.htm").Result.Content.ReadAsStreamAsync()).Result;
 using (var fileStream = new FileStream("D://data.txt", FileMode.Create, FileAccess.Write))
 {
     client.CopyTo(fileStream);
 }

Full Working Code:-

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Stream client = Task.Run(()=>new HttpClient().GetAsync("http://www.hkex.com.hk/eng/stat/dmstat/dayrpt/hsio180629.htm").Result.Content.ReadAsStreamAsync()).Result;
            using (var fileStream = new FileStream("D://data.txt", FileMode.Create, FileAccess.Write))
            {
                client.CopyTo(fileStream);
            }
        }
    }
}

With Await

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            data();
            Console.ReadKey();
        }
        public static async void data()
        {
            var client = await new HttpClient().GetAsync("http://www.hkex.com.hk/eng/stat/dmstat/dayrpt/hsio180629.htm");
            var data= await client.Content.ReadAsStreamAsync();
            using (var fileStream = new FileStream("D://data.txt", FileMode.Create, FileAccess.Write))
            {
                data.CopyTo(fileStream);
            }
        }
    }
}


来源:https://stackoverflow.com/questions/51133927/c-sharp-webclient-cannot-download-text-from-web

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!