Desktop apps can also provide HTTP file downloads

Source: Internet
Author: User
Tags urlencode

In the past, we must know that in the Web application, we may encounter the provision of file download function requirements, such as I used to do a customer license management system, customer purchase ERP system, usually we will be based on the machine code of the customer's machine to generate a license file, and this license file is time-limited , expires after one year, the customer will need to re-obtain the license after expiration to indicate the continued use of our super Bull B product, and if the customer no longer acquires the license, the customer is no longer using our Super Bull B product.

Later, I think, yes, we can get a Web application, let the customer log in, enter the machine code, automatically generate the license file, and then the customer click on the page to download on the line. Providing download functionality is actually very common, like many software download stations.

However, have we considered that if we write an application that only provides a few features related to HTTP downloads, we don't seem to need to make a Web site on the machine to get a server. Usually this is the case, a small window program can be finished. So, the idea of using a desktop application to provide HTTP downloads is a thought.

In fact, this implementation is not complicated, A HttpListener class is provided under the System.Net namespace, which listens for incoming HTTP requests from the client and then returns a HttpListenerContext object that can be used to process the request through the HttpListenerContext object /responds to related objects.

According to this idea, we can also easily provide the download function, the original and the Web is the same, that is, in response to the request to insert the Content-disposition header, the value of attachment;filename=< file name > method can be implemented.

[CSharp]View PlainCopy
  1. Private async void Btnlisten_click (object sender, EventArgs e)
  2. {
  3. HttpListener listener = new HttpListener ();
  4. Listener.  Prefixes.add ("http://+:80/download/");
  5. Listener. Start ();
  6. btnlisten.enabled = false;
  7. HttpListenerContext context = await listener. Getcontextasync ();
  8. if (context! = null)
  9. {
  10. //Add Content-disposition header
  11. Context. Response.appendheader ("content-disposition", "attachment;filename=" + webutility.urlencode (  Path.getfilename (Lblfilepath.text));
  12. Try
  13. {
  14. using (FileStream stream = File.openread (lblfilepath.text))
  15. {
  16. //Add content specifier
  17. Context. Response.ContentType = MediaTypeNames.Application.Octet;
  18. //Content length
  19. Context. Response.contentlength64 = stream. Length;
  20. //Postback data to client
  21. byte[] buffer = new byte[1024];
  22. int n = stream. Read (buffer, 0, buffer.  Length);
  23. While (n > 0)
  24. {
  25. Context. Response.OutputStream.Write (buffer, 0, N);
  26. n = stream. Read (buffer, 0, buffer. Length);
  27. }
  28. Context. Response.close (); //Off
  29. }
  30. }
  31. catch (Exception ex)
  32. {
  33. MessageBox.Show (ex. Message);
  34. }
  35. }
  36. Listener. Stop (); //Stop monitoring
  37. btnlisten.enabled = true;
  38. }

Encoding filename with Webutility.urlencode when setting filename prevents garbled characters when the file name contains Chinese.

and send the file to the client is much simpler, and ordinary flow operation is no different, The data read from the file is written to the Response.outputstream stream, and after it is sent, the Close method is called to close the Httplistenerresponse object, so the processing is completed and no more resources are required to open it.

The listener address is http://+:80/download/, which means that HttpListener receives requests for all host names on port 80, and adds download/in the subsequent path only to not conflict with the default localhost address of IIS. Because I turned on IIS.

After running, select a file and then click the button to start listening.

Then enter http://localhost/download/in the browser, press ENTER, you can test the download.

Desktop apps can also provide HTTP file downloads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.