Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c# - How can i download a website content to a string?

I tried this and i want that the source content of the website will be download to a string:

public partial class Form1 : Form
    {
        WebClient client;
        string url;
        string[] Search(string SearchParameter);


        public Form1()
        {
            InitializeComponent();

            url = "http://chatroll.com/rotternet";
            client = new WebClient();




            webBrowser1.Navigate("http://chatroll.com/rotternet");
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        static void DownloadDataCompleted(object sender,
           DownloadDataCompletedEventArgs e)
        {



        }


        public string SearchForText(string SearchParameter)
        {
            client.DownloadDataCompleted += DownloadDataCompleted;
            client.DownloadDataAsync(new Uri(url));
            return SearchParameter;
        }

I want to use WebClient and downloaddataasync and in the end to have the website source content in a string.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

No need for async, really:

var result = new System.Net.WebClient().DownloadString(url)

If you don't want to block your UI, you can put the above in a BackgroundWorker. The reason I suggest this rather than the Async methods is because it is dramatically simpler to use, and because I suspect you are just going to stick this string into the UI somewhere anyway (where BackgroundWorker will make your life easier).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...