问题
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