Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.
Posted
Updated 6-Jan-11 8:48am
v3
Comments
Brian C Hart 6-Jan-11 14:43pm    
My hunch is that this sounds a lot like a homework assignment. In my view, it's nothing that the docs can't help you out with.
Sandeep Mewara 6-Jan-11 14:48pm    
Any effort?
Manfred Rudolf Bihy 6-Jan-11 14:59pm    
If I didn't mess up with the counting I already got three questions here:
1. Download a file from the internet
2. Playing that file (mp3 or what)
3. Showing an icon in button
Should I dare OP to add another one. Why would I do this? You see three is a prime number and OP's questions aren't. So i guess if OP adds another one, ...

1 solution

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

C#
/*
    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


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?
 
Share this answer
 
v10
Comments
Sergey Alexandrovich Kryukov 6-Jan-11 15:43pm    
Note: wrong syntax coloration at the end is probably a result of incorrect processing of quotation character inside string.

The code itself compiles and works correctly.
fjdiewornncalwe 6-Jan-11 18:06pm    
Wow... You can't get any more complete an answer than this.
Sergey Alexandrovich Kryukov 7-Jan-11 3:01am    
Yes, I can. But why?
Thank you, Marcus.
Sergey Alexandrovich Kryukov 12-Jan-11 0:49am    
Fixed syntax coloring :-)
samadblaj 25-Aug-12 14:18pm    
limit the bandwidth For all applications?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900