Архив рубрики: Скачать файл из Интернет

C#: скачиваем файлы из Интернет


Пример кода для простого скачивания файлов из Интернет (например файла http://stroustrup.com/Programming/PPP2code/std_lib_facilities.h). Сетевые настройки при этом считываются из настроек Internet Explorer.




static voidMain(string[] args) {
    String file_name = Path.GetRandomFileName();
    String full_path = Environment.ExpandEnvironmentVariables(
        Path.Combine(@"%LocalAppData%Temp", file_name));

    using (WebClientclient = new WebClient()) {
        String uri = "http://stroustrup.com/Programming/PPP2code/std_lib_facilities.h";
        var proxyUri = WebRequest.GetSystemWebProxy()
            .GetProxy(new Uri(uri));
        client.Proxy = new WebProxy(proxyUri);
        client.Proxy.Credentials = CredentialCache.DefaultCredentials;
        try{
            client.DownloadFile(uri, full_path);
        }
        catch(Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
    Console.WriteLine("The result file: {0}", full_path);
    Console.WriteLine("Press any key for exit.");
    Console.ReadKey();
}



C#: скачиваем файлы из Интернет


Пример кода для простого скачивания файлов из Интернет (например файла http://stroustrup.com/Programming/PPP2code/std_lib_facilities.h). Сетевые настройки при этом считываются из настроек Internet Explorer.




static voidMain(string[] args) {
    String file_name = Path.GetRandomFileName();
    String full_path = Environment.ExpandEnvironmentVariables(
        Path.Combine(@"%LocalAppData%\Temp", file_name));

    using (WebClientclient = new WebClient()) {
        String uri = "http://stroustrup.com/Programming/PPP2code/std_lib_facilities.h";
        var proxyUri = WebRequest.GetSystemWebProxy()
            .GetProxy(new Uri(uri));
        client.Proxy = new WebProxy(proxyUri);
        client.Proxy.Credentials = CredentialCache.DefaultCredentials;
        try{
            client.DownloadFile(uri, full_path);
        }
        catch(Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
    Console.WriteLine("The result file: {0}", full_path);
    Console.WriteLine("Press any key for exit.");
    Console.ReadKey();
}