如何从互联网下载文件 [英] how to download a file from internet

查看:147
本文介绍了如何从互联网下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Net Compact Framework中,是否有一种对象方法可以让我从Internet下载文件?示例:下载音乐(mp3),如果我想播放此文件,该怎么办?
我正在用C#编写的Windows Mobile应用程序上工作,我想在按钮上插入图标,但是我不知道该怎么做.感谢您的帮助.

In Net Compact Framework, Is there a method of object which allow me to download a file from internet whether or not ? Example: download a music(mp3), if I want play this file, how can i do this ?
I am working on a windows mobile application written with C#, I want insert icon to button but I don''t know how to do this. Thanks for your help.

推荐答案

提供自己的代码(尚未100%完善)-随时进行改进:

Giving out my own code (not 100% polished yet) -- feel free to improve:

/*
    HttpDownloader --
       with ability to continue downloading partially downloaded file
    Copyright (C) 2006-2011 by Sergey A Kryukov,
    http://www.sakryukov.org
*/
using System;
using System.Net;
using System.IO;

namespace HttpDownloader {

    class HttpDownloadMain {

        const string NumericFormat = "###,###,###,###,###,###,###"; 
           //more than enough for uint64:
           //18,446,744,073,709,551,615 max

        static string CreateFormat(
          string preFormat, string placeholder) {
            return preFormat.Replace(placeholder, NumericFormat);
        } //CreateFormat

        static string ConvertUrlToFileName(string url) {
            string[] terms = url.Split(
                new string[] { ":", "//" },
                StringSplitOptions.RemoveEmptyEntries);
            string fname = terms[terms.Length - 1];
            fname = fname.Replace('/', '.');
            return fname;
        } //ConvertUrlToFileName

        static long GetExistingFileLength(string filename) {
            if (!File.Exists(filename)) return 0;
            FileInfo info = new FileInfo(filename);
            return info.Length;
        } //GetExistingFileLength

        static void DownloadOne(
          string url, string existingFilename, bool quiet) {
            HttpWebRequest webRequest;
            HttpWebResponse webResponse;
            IWebProxy proxy = null; //SA???
            string fmt = CreateFormat(
                "{0}: {1:#} of {2:#} ({3:g3}%)", "#");
            FileStream fs = null;
            try {
                string fname = existingFilename;
                if (fname == null)
                    fname = ConvertUrlToFileName(url);
                webRequest = (HttpWebRequest)WebRequest.Create(url);
                long preloadedLength = GetExistingFileLength(fname);
                if (preloadedLength > 0)
                    webRequest.AddRange((int)preloadedLength);
                webRequest.Proxy = proxy; //SA??? or DefineProxy
                webResponse = (HttpWebResponse)webRequest.GetResponse();
                fs = new FileStream(
                    fname, FileMode.Append, FileAccess.Write);
                long fileLength = webResponse.ContentLength;
                string todoFormat = CreateFormat(
                    @"Downloading {0}: {1:#} bytes...", "#");
                Console.WriteLine();
                Console.WriteLine(todoFormat, url, fileLength);
                Console.WriteLine(
                    "Pre-loaded: preloaded length {0}",
                    preloadedLength);
                Console.WriteLine("Remaining length: {0}", fileLength);
                Stream strm = webResponse.GetResponseStream();
                int arrSize = 10 * 1024 * 1024; //SA???                 
                byte[] barr = new byte[arrSize];
                long bytesCounter = preloadedLength;
                string fmtPercent = string.Empty;
                while (true) { //SA???
                    int actualBytes = strm.Read(barr, 0, arrSize);
                    if (actualBytes <= 0)
                        break;
                    fs.Write(barr, 0, actualBytes);
                    bytesCounter += actualBytes;
                    double percent = 0d;
                    if (fileLength > 0)
                        percent =
                            100.0d * bytesCounter /
                            (preloadedLength + fileLength);
                    if (!quiet)
                        Console.WriteLine(
                             fmt,
                             fname,
                             bytesCounter,
                             preloadedLength + fileLength,
                             percent);
                } //loop
                Console.WriteLine(@"{0}: complete!", url);
            } catch (Exception e) {
                Console.WriteLine(
                     "{0}: {1} '{2}'",
                     url, e.GetType().FullName,
                     e.Message);
            } finally {
                if (fs != null) {
                    fs.Flush();
                    fs.Close();
                } //if
            } //exception
        } //DownloadOne

        static void Main(string[] args) {
            Console.WriteLine(
               "Usage: >HTTPDownloader <http_url> [<output_file_name>]");
            if (args.Length < 1) return;
            string url = args[0];
            string existingFileName = null;
            if (args.Length > 1)
                existingFileName = args[1];
            DownloadOne(url, existingFileName, false);
        } //Main

    } //class HttpDownloadMain

} //namespace HttpDownloader



该代码允许继续下载部分下载的文件(重要!).可行!


坦白说,代码仍然具有原型质量:硬编码的字符串,一些其他立即数等,但是通过这种方式,它们全都保存在一个文件中.而且,它很稳定,为我服务很好.它可以作为派生项目的源服务器(请注明来源).

您还需要FTP吗?



The code allows to continue downloading partially downloaded files (Important!). It works!


Frankly, the code is still of a prototype quality: hard-coded strings, some other immediate constants, etc., but this way it is all in one file. Also, it is stable and served me well. It can server as as source for derived project (please credit my original).

Do you need FTP as well?


这篇关于如何从互联网下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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