C WebClient Class Usage Example

  • 2021-07-09 09:03:34
  • OfStack

The incoming project will implement a link page that can invoke the specified project in windows service. Because you are accessing the page using an ie browser or another browser, you think of using the webclient class.

If you only want to request files from a specific URI, use WebClient, which is the simplest. NET class, which uses only one or two commands to perform basic operations. NET FRAMEWORK currently supports uri starting with http:, https, and file: identifiers.

WebClient Download File

There are two ways to download files using webclient. The specific method depends on the processing method of file contents. If you only want to save files to disk, use downloadfile () method, which has two parameters, namely, the requested uri and the data storage location of the requested file.

More commonly, the application needs to process the data retrieved from the web site, using the OpenRead method, which returns an Stream object, which can then be fetched into memory from the data stream with an Stream object.

Example: OpenRead (string uri);


OpenRead(string uri)
 #region  Read the specified uri Adj. html
    /// <summary>
    ///  Read the specified uri Adj. html
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button4_Click(object sender, EventArgs e)
    {
      WebClient wc = new WebClient();
      string uri = "http://127.0.0.1/rss/sina.aspx";
      Stream stream = wc.OpenRead(uri);
      StreamReader sr = new StreamReader(stream);
      string strLine = "";
      while ((strLine = sr.ReadLine()) != null)
      {
        this.listBox1.Items.Add(strLine);
      }
      sr.Close();
    }
    #endregion

Example: OpenWriter (string uri, string method);


OpenWriter(string uri,string method)
#region  Open 1 Writes data to the uri
    /// <summary>
    ///  Open 1 Writes data to the uri
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button1_Click(object sender, EventArgs e)
    {
      WebClient wc = new WebClient();
      string uri = "http://192.168.0.35/cims30/rss.txt";
      Stream stream = wc.OpenWrite(uri, "PUT");
      StreamWriter sw = new StreamWriter(stream);
      sw.WriteLine("HelloWorldHelloWorldHelloWorldHelloWorld");
      sw.Flush();
      sw.Close();
      MessageBox.Show("OK");
    }
    #endregion

openwriter method returns a writable data stream, which is convenient for users to send data to uri. You can specify the method for users to send data to the host, and the default is post. The above example assumes that there is a writable directory on the server at 0.35. This code is to create rss. txt file under this directory, and its content is "HelloWorldHelloWorldHelloWorldHelloWorld"

Upload a file

The WebClient class provides UploadFile () and UploadData () methods, which you can use when you need to post an HTML form or upload an entire file. The Uploadfile () method uploads the file to the specified location, where the file name has been given, and the uploaddata () method uploads the binary data provided by the byte array to the specified uri;

Example: Upload a file


#region  Uploads a local file to the specified uri
    /// <summary>
    ///  Uploads a local file to the specified uri
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button2_Click(object sender, EventArgs e)
    {
      WebClient wc = new WebClient();
      string targetPath = "http://127.0.0.1/rss/Data Configuration.zip";
      string sourcePath = "d:\\Data Configuration.zip";
      this.label1.Text = string.Format("uploading {0} to {1}", targetPath, sourcePath);
      byte[] bt = wc.UploadFile(targetPath, "PUT", sourcePath);
      MessageBox.Show("OK");
    }
    #endregion


    #region  Uploads a data buffer to a specified resource 
    /// <summary>
    ///  Uploads a data buffer to a specified resource 
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void button3_Click(object sender, EventArgs e)
    {
      WebClient wc = new WebClient();
      string targetPath = "http://127.0.0.1/rss/kaifeng.jpg";
      string sourcePath = @"C:\test.jpg";
      FileStream fs = new FileStream(sourcePath, FileMode.Open, FileAccess.Read);
      byte[] bt = new byte[fs.Length];
      fs.Read(bt, 0, bt.Length);
      wc.UploadData(targetPath, "PUT", bt);
    }
    #endregion

webclient has limited functionality, especially the inability to use authentication certificates, which leads to problems when uploading data. Nowadays, many sites will not accept uploaded files without authentication. Although it is possible to add header information to the request and check the header information in the corresponding one, this is limited to checking in the general sense, and webclient does not specifically support any one protocol. This is because webclient is a very 1-like class that can send requests and accept them using any protocol, and it cannot handle any features specific to any protocol.


Related articles: