C# webclient 无法从 web 下载文本 [英] C# webclient cannot download text from web

查看:31
本文介绍了C# webclient 无法从 web 下载文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,从this网站.但是当我在 Visual Studio 中对其进行测试时,出现了一些错误:

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:

值不能为空.参数名称:solutionDirectory

Value cannot be null. Parameter name: solutionDirectory

这是我的代码:

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);
    }
}

推荐答案

请使用 HttpClient 与 webClient 相比非常好的选项您的问题听起来像是您的项目 (vcxproj) 文件设置不正确.

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.

在这里你可以找到真正的区别

 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);
 }

完整的工作代码:-

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);
            }
        }
    }
}

等待

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);
            }
        }
    }
}

这篇关于C# webclient 无法从 web 下载文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆