コード例 #1
0
        public override void StopDownload()
        {
            _downloadThread?.Abort();
            _webClient?.CancelAsync();
            _webClient?.Dispose();

            OnDownloadItemDownloadCompleted(new DownloadCompletedEventArgs(true, true));
        }
コード例 #2
0
        public void Complete()
        {
            this.IsCompleted   = true;
            this.IsDownloading = false;
            this.Speed         = 0;
            client?.Dispose();


            if (!StopDownload)
            {
                PaperDownloadComplete?.Invoke();
                ///关闭 等待窗
                Application.Current.Dispatcher.Invoke(new Action(() => { dialogSession?.Close(); }));
            }
        }
コード例 #3
0
 private void Dispose(bool disposing)
 {
     if (disposing)
     {
         _webClient?.Dispose();
     }
 }
コード例 #4
0
 static void Main()
 {
     WebClient webClient = new WebClient();
         try
         {
             webClient.DownloadFile("http://telerikacademy.com/Content/Images/news-img01.png", @"news-img01.png");
             Console.WriteLine("Done"); // image is downloaded in your current directory.
         }
         catch (ArgumentNullException)
         {
             Console.WriteLine("The address parameter is null");
         }
         catch (WebException)
         {
             Console.WriteLine("File does not exist, its name is null or empty, address is invalid, or an error occurred while downloading data");
         }
         catch (NotSupportedException)
         {
             Console.WriteLine("The method has been called simultaneously on multiple threads");
         }
         finally
         {
             webClient.Dispose();
         }
 }
コード例 #5
0
        private Version GetOnlineVersion()
        {
            WebClient client = null;
            Version   vers   = new Version();

            try
            {
                client = new WebClient();

                string data = client.DownloadString("http://lolwis.bplaced.net/bcs/version.info");

                int major    = int.Parse(data.Split('.')[0]);
                int minor    = int.Parse(data.Split('.')[1]);
                int build    = int.Parse(data.Split('.')[2]);
                int revision = int.Parse(data.Split('.')[3]);

                vers = new Version(major, minor, build, revision);
            }
            catch (Exception)
            {
                MessageBox.Show("Onlineversion konnte nicht bestimmt werden!", "Fehler", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                client?.Dispose();
            }

            return(vers);
        }
コード例 #6
0
    static void Main()
    {
        Console.WriteLine("Task 04 - Download a file from given URI\n\n");

        string uri = "http://www.devbg.org/img/Logo-BASD.jpg";

        Console.WriteLine();

        Console.Write("Please enter full URI to download (or press enter for default): ");
        string file = Console.ReadLine();
        if (file.Length == 0) file = uri;
        WebClient client = null;
        try
        {
            string filename = Path.GetFullPath(".") + @"\" + Path.GetFileName(file);
            Console.WriteLine("\nDownloading {0}\n\nDestination: {1}\n\n", file, filename);
            client = new WebClient();
            client.DownloadFile(file, filename);
        }
        catch (SystemException se)
        {
            Console.WriteLine("Exception: " + se.Message);
        }
        finally
        {
            if (client != null) client.Dispose();
        }

        Console.WriteLine("\n\nPress Enter to finish");
        Console.ReadLine();
    }
コード例 #7
0
    static void Main()
    {
        Console.Write("Please enter the path: ");
        string path = Console.ReadLine();
        string fileName = "ninja.gif";
        WebClient myWebClient = new WebClient();

        try
        {
            myWebClient.DownloadFile(path, fileName);
            Console.WriteLine(@"The file is downloaded in Project\bin\Debug!");
        }
        catch (WebException)
        {
            Console.WriteLine("The adress is invalid.");
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("The address parameter is null.");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("The method has been called simultaneously on multiple threads.");
        }
        finally
        {
            myWebClient.Dispose();
        }
    }
コード例 #8
0
 static void Main()
 {
     WebClient client = new WebClient();
     try
     {
         client.DownloadFile("http://telerikacademy.com/Content/Images/news-img01.png", "ninja.png");
     }
     catch (UriFormatException e)
     {
         Console.WriteLine(e.Message);
     }
     catch (HttpListenerException e)
     {
         Console.WriteLine(e.Message);
     }
     catch (WebException e)
     {
         Console.WriteLine(e.Message);
     }
     catch (UnauthorizedAccessException e)
     {
         Console.WriteLine(e.Message);
     }
     catch (NotSupportedException e)
     {
         Console.WriteLine(e.Message);
     }
     finally
     {
         client.Dispose();
     }
 }
コード例 #9
0
        /// <summary>
        /// 使用Http方式的异步方法下载远程文件并保存在本地.
        /// </summary>
        /// <param name="sourceFile">需要下载文件的Uri地址</param>
        /// <param name="destinationFile">保存文件的全路径名</param>
        /// <param name="downloadFileCompleted">文件下载完成后需要执行的委托,可以在此步骤完成相关状态的改变</param>
        public static void DownLoadFileAsync(this string sourceFile, string destinationFile, Action <AsyncCompletedEventArgs> downloadFileCompleted)
        {
            WebClient client = null;

            try {
                client = new WebClient();
                client.DownloadFileCompleted += (s, a) => {
                    try {
                        FileInfo fi = new FileInfo(destinationFile);
                        //如果文件存在且没有内容,则删除该文件
                        if (fi.Exists && fi.Length <= 0)
                        {
                            fi.Delete();
                        }

                        downloadFileCompleted(a);
                    }
                    finally {
                        client?.Dispose();
                    }
                };

                client.DownloadFileAsync(new Uri(sourceFile), destinationFile, new { Source = sourceFile, Destination = destinationFile });
            }
            catch (Exception ex) {}
        }
コード例 #10
0
 static void Main(string[] args)
 {
     WebClient downloader = new WebClient();
     string uri = "http://www.devbg.org/img/Logo-BASD.jpg";
     string destination = Directory.GetCurrentDirectory() + @"\Logo-BASD.jpg";
     try
     {
         downloader.DownloadFile(uri, destination);
     }
     catch (WebException we)
     {
         Console.WriteLine(we.Message);
     }
     catch (NotSupportedException nse)
     {
         Console.WriteLine(nse.Message); ;
     }
     catch (ArgumentException ae)
     {
         Console.WriteLine(ae.Message);
     }
     finally
     {
         downloader.Dispose();
     }
 }
コード例 #11
0
ファイル: AmiiboAPI.cs プロジェクト: ganderm/emuguiibo-cross
        public void LoadAllAmiibos()
        {
            WebClient client = new WebClient();

            try
            {
                JObject json = JObject.Parse(client.DownloadString(AMIIBO_API_URL));
                AllAmiibos.Clear();
                foreach (JToken amiibo in json["amiibo"])
                {
                    AllAmiibos.Add(new Amiibo
                    {
                        AmiiboName    = amiibo["name"].ToString(),
                        SeriesName    = amiibo["amiiboSeries"].ToString(),
                        CharacterName = amiibo["character"].ToString(),
                        ImageURL      = amiibo["image"].ToString(),
                        AmiiboId      = amiibo["head"].ToString() + amiibo["tail"].ToString()
                    });
                }

                Series = AllAmiibos.AsQueryable().Select(amiibo => amiibo.SeriesName.ToString()).Distinct().ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                client?.Dispose();
            }
        }
コード例 #12
0
ファイル: Time.cs プロジェクト: hype-armor/Fancy
    private DateTime GetTimeFromDDG()
    {
        //https://duckduckgo.com/?q=what+time+is+it
        WebClient wc = new WebClient();
        try
        {
            char[] separators = new char[] { '<', '>', '\\', '/', '|' };

            string timeisPage = wc.DownloadString("https://duckduckgo.com/html/?q=what%20time%20is%20it");
            timeisPage = timeisPage.Remove(0, timeisPage.IndexOf("\n\n\t\n\n\n\n            ") + 19);
            string[] timeisSplit = timeisPage.Split(separators, StringSplitOptions.RemoveEmptyEntries);
            string Time = timeisSplit[0].Remove(timeisSplit[0].Length - 5);
            DateTime result;
            if (DateTime.TryParse(Time, out result))
            {
                return result;//.ToString("t");
            }
            throw new Exception();
        }
        catch
        {
            return DateTime.Now;//.ToString("t");
        }
        finally
        {
            wc.Dispose();
            GC.Collect();
        }
    }
コード例 #13
0
 static void Main()
 {
     WebClient webClient = new WebClient();
     Console.WriteLine("Enter file url: ");
     string downloadSource = Console.ReadLine();
     Console.WriteLine("Enter destination on local hard drive. Specify file name and extension: ");
     string downloadDestination = Console.ReadLine();
     try
     {
         webClient.DownloadFile(downloadSource, downloadDestination);
     }
     catch (System.Net.WebException)
     {
         Console.WriteLine("Error accessing the network.");
     }
     catch (System.NotSupportedException)
     {
         Console.WriteLine("Method not supported or failed attempt to read, seek or write to a stream.");
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("A null reference cannot be accepted by this method!");
     }
     catch (ArgumentException)
     {
         Console.WriteLine("The path you entered is invalid.");
     }
     finally
     {
         webClient.Dispose();
     }
 }
コード例 #14
0
 static void Main()
 {
     WebClient webClient = new WebClient();
     Console.Write("Please enter URL: ");
     string url = Console.ReadLine();
     try
     {
         string[] splittedURL = url.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
         string name = splittedURL[splittedURL.Length - 1];
         webClient.DownloadFile(url, name);
         Console.WriteLine("The file is downloaded successfuly!");
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("Please enter valid url!");
     }
     catch (WebException)
     {
         Console.WriteLine("Problem with accessing the network! The url: {0} might be wrong!", url);
     }
     catch (NotSupportedException)
     {
         Console.WriteLine("Does not support the invoked functionality!");
     }
     finally
     {
         webClient.Dispose();
     }
 }
コード例 #15
0
    static void Main()
    {
        // we have some work with namespace Net and webclient class
        WebClient webClient = new WebClient();

        try
        {
            //downloading file from internet
            //first argument is URL from which we will procced
            //second is the name with which we will save it on the comp
            webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "logo.jpg");
        }
            //signature of exceptions specified for webclient class
        catch(ArgumentNullException ANE)
        {
            Console.WriteLine(ANE.Message);
        }
        catch(WebException WE)
        {
            Console.WriteLine(WE.Message);
        }
        catch(NotSupportedException NSE)
        {
            Console.WriteLine(NSE.Message);
        }
        finally
        {
            webClient.Dispose();
            Console.WriteLine("Good Bye");
        }
    }
コード例 #16
0
    static void Main()
    {
        Console.WriteLine("Enter URL to download from: ");
        string adress = Console.ReadLine();
        Console.WriteLine("Enter name for the file: ");
        string fileName = Console.ReadLine();

        WebClient webClient = new WebClient();
        try
        {
            Console.WriteLine("Downloading file from \"{0}\" .......\n\n", adress);
            // Download the Web resource and save it into the current filesystem folder.
            webClient.DownloadFile(adress, fileName);
            Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, adress);
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("Either adress parameter is null or filename parameter is null!");
        }
        catch (WebException)
        {
            Console.WriteLine("The URI adress is invalid,filename is null or empty or an error occurred while downloading data!");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("The method has been called simultaneously on multiple threads.");
        }
        finally
        {
            webClient.Dispose();
        }
    }
コード例 #17
0
 protected override void PostStop()
 {
     lock (_client)
     {
         _client?.Dispose();
     }
 }
コード例 #18
0
    static void Main()
    {
        WebClient downloader = new WebClient();
        string url = "http://www.devbg.org/img/Logo-BASD.jpg";
        string fileName = "downloadedPicture.jpg";

        try
        {
            downloader.DownloadFile(url, fileName);
            Console.WriteLine("The file was successfully downloaded from {0} to the current directory of the program.", url);
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("The url parameter is null.");
        }
        catch (WebException)
        {
            Console.WriteLine("The fileName is null or Empty, the file does not exist or an error occurred while downloading data.");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("The method has been called simultaneously on multiple threads.");
        }
        finally
        {
            downloader.Dispose();
        }
    }
コード例 #19
0
ファイル: DownlaodFile.cs プロジェクト: koko-9898/Projects
 private static void ReadAndDownloadFile()
 {
     WebClient wc = new WebClient();
     try
     {
         string link = @"http://www.devbg.org/img/Logo-BASD.jpg";
         wc.DownloadFile(link, "../../pic.jpg");
     }
     catch (ArgumentNullException ane)
     {
         Console.WriteLine(ane.Message);
     }
     catch (WebException we)
     {
         Console.WriteLine(we.Message);
     }
     catch (NotSupportedException nse)
     {
         Console.WriteLine(nse.Message);
     }
     finally
     {
         wc.Dispose();
     }
 }
コード例 #20
0
    static void Main(string[] args)
    {
        string url = "http://telerikacademy.com/Content/Images/news-img01.png";
        string fileName = "TelerikNinja.png";
        WebClient downloadPic = new WebClient();

        try
        {
            downloadPic.DownloadFile(url, fileName);
            Console.WriteLine("The picture is saved at {0}.", Directory.GetCurrentDirectory());
        }
        catch (UnauthorizedAccessException exception)
        {
            Console.WriteLine(exception.Message);
        }
        catch (NotSupportedException exception)
        {
            Console.WriteLine(exception.Message);
        }
        catch (WebException exception)
        {
            Console.WriteLine(exception.Message);
        }
        catch (ArgumentException exception)
        {
            Console.WriteLine(exception.Message);
        }
        finally
        {
            downloadPic.Dispose();
        }
    }
コード例 #21
0
    static void Main()
    {
        string remoteUri = "http://telerikacademy.com/Content/Images/";
        string fileName = "news-img01.png";
        string webResource = null;
        WebClient myWebClient = new WebClient();
        webResource = remoteUri + fileName;


        Console.WriteLine("Downloading File \"{0}\" from \"{1}\" .......\n", fileName, webResource);
        try
        {
            myWebClient.DownloadFile(webResource, fileName);
            Console.WriteLine("Successfully Downloaded File \"{0}\" from \"{1}\"", fileName, webResource);
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("No address given.");
        }
        catch (WebException)
        {
            Console.WriteLine("The file does not exist or the name is empty.");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("The method has been called simultaneously on multiple threads.");
        }
        finally
        {
            myWebClient.Dispose();
        }
        Console.WriteLine();
    }
コード例 #22
0
        public void Test_DownloadTextFile_ValidateContentInspection_Success()
        {
            const string Url = "https://raw.githubusercontent.com/stevemerckel/power-change-alert/master/README.md";

            Console.WriteLine($"Url = {Url}");
            var downloadFile = Path.Combine(_workDirectory, new Uri(Url).Segments.Last());

            Console.WriteLine($"{nameof(downloadFile)} = {downloadFile}");
            WebClient wc = null;

            try
            {
                wc = new WebClient();
                var startOn = DateTime.Now;
                wc.DownloadFile(Url, downloadFile);
                var downloadTimeNeeded = DateTime.Now.Subtract(startOn);
                Console.WriteLine($"Finished downloading file after {downloadTimeNeeded.TotalMilliseconds} milliseconds");
            }
            finally
            {
                wc?.Dispose();
            }

            Assert.IsTrue(_sut.FileExists(downloadFile));
            Assert.IsTrue(new FileInfo(downloadFile).Length > 0, $"No content was found in '{downloadFile}'");
            Assert.IsFalse(_sut.IsFileBlocked(downloadFile));
            const string KnownSnipInTextFile = "Before Running or Debugging";
            var          fileContent         = _sut.ReadAllText(downloadFile);

            Assert.IsTrue(fileContent.Length > 0);
            Assert.IsTrue(fileContent.Contains(KnownSnipInTextFile, StringComparison.InvariantCulture), $"Could not find known text of '{KnownSnipInTextFile}'");
        }
コード例 #23
0
 static void Main()
 {
     Console.WriteLine("This program downloads a file from internet\n" +
         "by given URL from the user.");
     Console.Write("Please enter URL address: ");
     string URL = Console.ReadLine();
     Console.Write("Please enter file name: ");
     string file = Console.ReadLine();
     string fullAddress = URL + "/" + file;
     WebClient webClient = new WebClient();
     try
     {
         webClient.DownloadFile(fullAddress, file);
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("The address can not be null");
     }
     catch (WebException)
     {
         Console.WriteLine("Invalid address or empty file.");
     }
     catch (NotSupportedException)
     {
         Console.WriteLine("This method does not support simultaneous downloads.");
     }
     finally
     {
         webClient.Dispose();
     }
 }
コード例 #24
0
 //Write a program that downloads a file from Internet (e.g. http://www.devbg.org/img/Logo-BASD.jpg)
 //and stores it the current directory. Find in Google how to download files in C#. Be sure to catch
 //all exceptions and to free any used resources in the finally block.
 static void Main(string[] args)
 {
     string url = "http://www.devbg.org/img/Logo-BASD.jpg";
     string localPath = @Environment.CurrentDirectory + "\\Logo-BASD.jpg";
     WebClient webClient = new WebClient();
     try
     {
         webClient.DownloadFile(url, localPath);
     }
     catch (FormatException e)
     {
         Console.WriteLine(e.Message);
         Console.WriteLine(e.Data);
         Console.WriteLine(e.StackTrace);
     }
     catch (AccessViolationException e)
     {
         Console.WriteLine("You cannot save the file in this location {0}", localPath);
         Console.WriteLine(e.Message);
         Console.WriteLine(e.Data);
         Console.WriteLine(e.StackTrace);
     }
     finally
     {
         webClient.Dispose();
     }
 }
コード例 #25
0
 /// <inheritdoc cref="IDisposable.Dispose"/>
 public void Dispose(bool disposing)
 {
     if (disposing)
     {
         _webClient?.Dispose();
     }
 }
コード例 #26
0
ファイル: DownloadFile.cs プロジェクト: jesusico83/Telerik
    static void Main()
    {
        WebClient client = new WebClient();

        try
        {
            string adressAsString = "http://www.devbg.org/img/Logo-BASD.jpg";

            string location = "Image.jpg";

            client.DownloadFile(adressAsString, location);

            Console.WriteLine("The download is complete. You can find your file in bin/Debug");
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("The adress parameter is with null value");
        }
        catch (WebException)
        {
            Console.WriteLine("Invalid adress, the file name is empty or null, or the file does not exist");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("The method has been called simultaneously on multiple targets");
        }
        finally
        {
            client.Dispose();
        }
    }
コード例 #27
0
        // TODO: add tests for parsed data
        /// <summary>
        /// Returns array of the model type T from shared by the link Google Sheet documnet.
        /// </summary>
        /// <typeparam name="T">Model type of imported data</typeparam>
        /// <param name="link">Link to the shared google sheet file</param>
        /// <param name="ct">CancellationToken</param>
        /// <returns>Array of the model type data contained in Google Sheet</returns>
        public static async Task <T[]> FromGoogleSheet <T>(string link, CancellationToken ct)
        {
            WebClient client = null;

            try
            {
                var file          = $"{Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)}\\Regata\\tmpSet.csv";
                var key           = new Uri(link).AbsolutePath.Split('/')[3];
                var performedLink = $"https://docs.google.com/spreadsheets/d/{key}/gviz/tq?tqx=out:csv&sheet=SamplesList";
                client = new WebClient();
                await Task.Run(() => client.DownloadFile(new Uri(performedLink), file), ct);

                return(await Task.Run(() => FromCSVToArray <T>(file), ct));
            }
            catch (IndexOutOfRangeException)
            {
                throw new IndexOutOfRangeException("Something wrong with provided link. Make sure the link contains the key i.e. file has shared access. For example, try to open it in non default browser in your system.");
            }
            catch (UriFormatException)
            {
                throw new WebException("Something wrong with provided link. Make sure the link contains the key i.e. file has shared access. For example, try to open it in non default browser in your system.");
            }
            catch (WebException)
            {
                throw new WebException("Something wrong with provided link. Make sure the link contains the key i.e. file has shared access. For example, try to open it in non default browser in your system.");
            }
            finally
            {
                client?.Dispose();
            }
        }
コード例 #28
0
ファイル: DownloadFile.cs プロジェクト: stefan-er/CSharp
    static void Main()
    {
        string address = "http://www.devbg.org/img/Logo-BASD.jpg";
        string fileName = @"d:\Logo-BASD.jpg";
        using (WebClient webClient = new WebClient())

        try
        {
            webClient.DownloadFile(address, fileName);
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("The address parameter is null.\n-or-\nThe fileName parameter is null");
        }
        catch (WebException)
        {
            Console.WriteLine("The address is invalid.");
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("	The method has been called simultaneously on multiple threads.");
        }
        finally
        {
            webClient.Dispose();
        }
    }
コード例 #29
0
        public static async Task <bool> TryDownloadFile(string URL, string filePath, int?timeout = null)
        {
            WebClient webClient         = null;
            CancellationTokenSource cts = null;

            try
            {
                webClient       = new WebClient();
                webClient.Proxy = null;
                if (timeout != null)
                {
                    cts = new CancellationTokenSource((int)timeout);
                    cts.Token.Register(() => webClient.CancelAsync());
                }

                await webClient.DownloadFileTaskAsync(URL, filePath);

                return(File.Exists(filePath));
            }
            catch (Exception ex)
            {
                Log.Error("FileManager.TryDownloadFile", ex.ToString());
                return(false);
            }
            finally
            {
                webClient?.Dispose();
                cts?.Dispose();
            }
        }
コード例 #30
0
 static void Main()
 {
     string decorationLine = new string('-', 80);
     Console.Write(decorationLine);
     Console.WriteLine("***Downloading a file from Internet and storing it in the current directory***");
     Console.Write(decorationLine);
     WebClient webClient = new WebClient();
     try
     {
         string remoteUri = "http://www.telerik.com/images/newsletters/academy/assets/";
         string fileName = "ninja-top.gif";
         string fullFilePathOnWeb = remoteUri + fileName;
         webClient.DownloadFile(fullFilePathOnWeb, fileName);
         Console.WriteLine("Downloading '{0}' from {1} is completed!", fileName, remoteUri);
         Console.WriteLine("You can find it in {0}.", Environment.CurrentDirectory);
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("No file address is given!");
     }
     catch (WebException webException)
     {
         Console.WriteLine(webException.Message);
     }
     catch (NotSupportedException)
     {
         Console.WriteLine("Downloading a file is in process! Cannot download multiple \nfiles simultaneously!");
     }
     finally
     {
         webClient.Dispose();
     }
 }
コード例 #31
0
    static void Main()
    {
        WebClient webClient = new WebClient();

            using (webClient)
            {
                try
                {
                    Console.WriteLine("Downloading file...");
                    webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"d:\myfile.jpg");
                    Console.WriteLine("Done.");
                }
                catch (ArgumentNullException an)
                {
                    Console.WriteLine("ArgumentNullException: " + an.Message);
                }
                catch (ArgumentException ae)
                {
                    Console.WriteLine("ArgumentException: " + ae.Message);
                }
                catch (WebException we)
                {
                    Console.WriteLine("WebException: " + we.Message);
                }
                catch (NotSupportedException ns)
                {
                    Console.WriteLine("NotSupportedException: " + ns.Message);
                }
                finally
                {
                    webClient.Dispose();
                    GC.Collect();
                }
            }
    }
コード例 #32
0
ファイル: DownloadFile.cs プロジェクト: damy90/Telerik-all
 static void Main()
 {
     string fileName="news-img01.png";
     string path = GetSavePath(fileName);
     string address = "http://telerikacademy.com/Content/Images/news-img01.png";
     WebClient client = new WebClient();
     try
     {
         client.DownloadFile(address, path);
         Console.WriteLine("File saved in {0}", path);
     }
     catch (ArgumentNullException)
     {
         Console.WriteLine("The address can not be null");
     }
     catch (WebException)
     {
         Console.WriteLine("Invalid address or file name.");
     }
     catch (NotSupportedException)
     {
         Console.WriteLine("Simultaneous downloads are not supported.");
     }
     finally
     {
         client.Dispose();
     }
 }
コード例 #33
0
    static void Main()
    {
        WebClient webClient = new WebClient();
        string linkToFile = @"http://www.devbg.org/img/Logo-BASD.jpg";
        try
        {
            webClient.DownloadFile( linkToFile,"logo.jpg");
        }

        catch (ArgumentNullException)
        {
            Console.WriteLine("You can't use null arguments");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("'{0}' is a wrong path", linkToFile);
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("Use different slashes for this operating system");
        }
        catch (WebException)
        {
            Console.WriteLine("Not file specified to save to");
        }
        finally
        {
            webClient.Dispose();
        }
    }
コード例 #34
0
 public static void CleanupWebClient(WebClient webClient)
 {
     webClient?.Headers.Clear();
     webClient?.Dispose();
     GC.Collect();
     GC.WaitForPendingFinalizers();
 }
コード例 #35
0
 static void Main()
 {
     Console.WriteLine("Enter the URL of the which you want to download:\nExample: \"http://www.d3bg.org/img/upload/tamplier/01.jpg\" ");
     Uri uri = new Uri(Console.ReadLine());
     string fileName = System.IO.Path.GetFileName(uri.LocalPath);
     WebClient webClient = new WebClient();
     try
     {
         // "../../" changes the default location of the downloaded file to two directories above!
         webClient.DownloadFile(uri, "../../" + fileName);
         Console.WriteLine("The file was successfully downloaded!\n!");
     }
     catch (WebException)
     {
         Console.WriteLine("Invalid adress or empty file.");
     }
     catch (NotSupportedException)
     {
         Console.WriteLine("");
     }
     finally
     {
         webClient.Dispose();
     }
 }
コード例 #36
0
        public void DownloadNext()
        {
            if (downloadQueue.Count > 0)
            {
                ThemeConfig theme = downloadQueue.Peek();

                if (theme.imagesZipUri.StartsWith("file://"))
                {
                    string themePath = (new Uri(theme.imagesZipUri)).LocalPath;
                    ThemeManager.CopyLocalTheme(theme, themePath,
                                                this.UpdateTotalPercentage);

                    downloadQueue.Dequeue();
                    DownloadNext();
                }
                else
                {
                    List <string> imagesZipUris = theme.imagesZipUri.Split('|').ToList();
                    client.DownloadFileAsync(new Uri(imagesZipUris.First()),
                                             theme.themeName + "_images.zip", imagesZipUris.Skip(1).ToList());
                }
            }
            else
            {
                client?.Dispose();
                this.Close();
            }
        }
コード例 #37
0
 /// <summary>
 ///     Delete the downloaded image.
 /// </summary>
 public void Dispose()
 {
     if (!string.IsNullOrWhiteSpace(Url))
     {
         File.Delete(Path);
     }
     _client?.Dispose();
 }
コード例 #38
0
ファイル: OrderService.cs プロジェクト: Crustquake/Zakupki
 public void Dispose()
 {
     if (!isDisposed)
     {
         _webClient?.Dispose();
         isDisposed = true;
     }
 }
コード例 #39
0
        public void Solve()
        {
            string problemToSolve = ErrorSelectionWindow.CurrentSelected;

            App.ErrorSelectionWindow.Close();
            _webClient?.Dispose();
            _webClient = new WebClient();
            switch (problemToSolve)
            {
            case "cbInstallLinks":
                InstallLink();
                break;

            case "cbMenu":
                MenuNotShowing();
                break;

            case "cbOrbwalkStutter":
                OrbwalkerStuttering();
                break;

            case "cbAuth":
                AuthFailed();
                break;

            case "cbBugSplat":
                BugSplat();
                break;

            case "cbInject":
                NotInjecting();
                break;

            case "cbStartError":
                ErrorStart();
                break;

            case "cbDependenciesReinstall":
                ReinstallDependencies();
                break;

            case "cbAppdata":
                ClearAppdata();
                break;

            case "cbReinstallKeepSettings":
                ReinstallLeaguesharpKeepSettings();
                break;

            case "cbReinstall":
                ReinstallLeaguesharp();
                break;

            case "cbResetSettings":
                ResetSettings();
                break;
            }
        }
コード例 #40
0
        /// <summary>
        /// Responsible to parse the XML and translates it to Location and WeatherData objects.
        /// It also initialize the location object with all relevant details.
        /// </summary>
        /// <param name="location"></param>
        /// <exception cref="WeatherDataServiceException">
        /// Thrown when method fail to initialize Location and Weatherdata from XML.</exception>
        /// <returns>WeatherData object with all relevant information</returns>
        private WeatherData ParseXmlToWeatherData(Location location)
        {
            WebClient client = null;

            try
            {
                client = new WebClient();
                string    xml = @client.DownloadString(UrlXmlAddress.ToString());
                XDocument doc = XDocument.Parse(xml);
                location.Initialize                     //fill out all missing data of location object
                (
                    doc.Descendants("city").Attributes("name").First().Value,
                    double.Parse(doc.Descendants("coord").Attributes("lon").First().Value),
                    double.Parse(doc.Descendants("coord").Attributes("lat").First().Value),
                    doc.Descendants("country").First().Value
                );
                return(new WeatherData                  //return WeatherData object with full data inside
                       (
                           location,
                           double.Parse(doc.Descendants("temperature").Attributes("value").First().Value),
                           double.Parse(doc.Descendants("humidity").Attributes("value").First().Value),
                           double.Parse(doc.Descendants("pressure").Attributes("value").First().Value),
                           doc.Descendants("clouds").Attributes("name").First().Value,
                           doc.Descendants("lastupdate").Attributes("value").First().Value,
                           double.Parse(doc.Descendants("speed").Attributes("value").First().Value) * 3.6,
                           doc.Descendants("speed").Attributes("name").First().Value,
                           doc.Descendants("direction").Attributes("name").First().Value
                       ));
            }
            catch (WebException)
            {
                throw new WeatherDataServiceException("Faild to connect to openweathermap.org");
            }
            catch (XmlException)
            {
                throw new WeatherDataServiceException("Failed to find the XML document");
            }
            catch (InvalidOperationException)
            {
                throw new WeatherDataServiceException("Failed to parse the XML");
            }
            catch (FormatException)
            {
                throw new WeatherDataServiceException("Failed to format the string to a number");
            }
            catch (Exception e)
            {
                throw new WeatherDataServiceException(e.Message);
            }
            finally
            {
                //Closing the connection to openweathermap.org
                client?.Dispose();

                //Restarting the address so next time we also get a correct url address
                UrlXmlAddress.Clear();
            }
        }
コード例 #41
0
 public void Dispose()
 {
     webClient?.Dispose();
     icr           = null;
     useraddress   = null;
     password      = null;
     serveraddress = null;
     accessUrlBase = null;
 }
コード例 #42
0
 protected override void Dispose(bool disposing)
 {
     if (disposing)
     {
         _wc?.Dispose();
         MovieEntries?.Clear();
         MovieEntries = null;
     }
     base.Dispose(disposing);
 }
コード例 #43
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _webClient?.Dispose();
                _webClient = null;

                _httpClient?.Dispose();
                _httpClient = null;
            }
        }
コード例 #44
0
            // Invoked when download completes, aborts or fails.
            private void DownloadCompleted(object sender, AsyncCompletedEventArgs e)
            {
                // Dispose web client.
                _client?.Dispose();
                _client = null;

                // Dispose of resources so download can be retried.
                if (e.Cancelled || e.Error != null)
                {
                    Dispose();
                }
            }
コード例 #45
0
 /// <summary>
 ///     Downloads the specified internet resource to a local file.
 /// </summary>
 /// <param name="srcUri">
 ///     The full path of the resource to download.
 /// </param>
 /// <param name="destPath">
 ///     The local destination path of the file.
 /// </param>
 /// <param name="userName">
 ///     The username associated with the credential.
 /// </param>
 /// <param name="password">
 ///     The password associated with the credential.
 /// </param>
 /// <param name="allowAutoRedirect">
 ///     <see langword="true"/> to indicate that the request should follow
 ///     redirection responses; otherwise, <see langword="false"/>.
 /// </param>
 /// <param name="cookieContainer">
 ///     The cookies associated with the request.
 /// </param>
 /// <param name="timeout">
 ///     The time-out value in milliseconds.
 /// </param>
 /// <param name="userAgent">
 ///     The value of the User-agent HTTP header.
 /// </param>
 /// <param name="checkExists">
 ///     <see langword="true"/> to check the file availability before downloading;
 ///     otherwise, <see langword="false"/>.
 /// </param>
 public void DownloadFile(Uri srcUri, string destPath, string userName = null, string password = null, bool allowAutoRedirect = true, CookieContainer cookieContainer = null, int timeout = 60000, string userAgent = null, bool checkExists = true)
 {
     try
     {
         if (srcUri == null)
         {
             throw new ArgumentNullException(nameof(srcUri));
         }
         if (IsBusy)
         {
             throw new NotSupportedException(ExceptionMessages.AsyncDownloadIsBusy);
         }
         var path = PathEx.Combine(destPath);
         if (File.Exists(path))
         {
             File.Delete(path);
         }
         try
         {
             _webClient = new WebClientEx(allowAutoRedirect, cookieContainer, timeout);
             if (!string.IsNullOrEmpty(userAgent))
             {
                 _webClient.Headers.Add("User-Agent", userAgent);
             }
             _webClient.DownloadFileCompleted   += DownloadFile_Completed;
             _webClient.DownloadProgressChanged += DownloadFile_ProgressChanged;
             Address  = srcUri;
             FileName = path.Split('\\').Last() ?? string.Empty;
             FilePath = path;
             if (checkExists && !Address.FileIsAvailable(userName, password, allowAutoRedirect, cookieContainer, timeout, userAgent))
             {
                 throw new PathNotFoundException(srcUri.ToString());
             }
             if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
             {
                 _webClient.Credentials = new NetworkCredential(userName, password);
             }
             _webClient.DownloadFileAsync(Address, FilePath);
             _stopwatch.Start();
         }
         finally
         {
             _webClient?.Dispose();
         }
     }
     catch (Exception ex) when(ex.IsCaught())
     {
         Log.Write(ex);
         HasCanceled = true;
         _stopwatch.Reset();
     }
 }
コード例 #46
0
        /// <summary>
        /// Responsible to parse the Json and translates it to Location and WeatherData objects.
        /// It also initialize the location object with all relevant details.
        /// </summary>
        /// <param name="location"></param>
        /// <exception cref="WeatherDataServiceException">
        /// Thrown when method fail to initialize Location and Weatherdata from Json.</exception>
        /// <returns>WeatherData object with all relevant information</returns>
        private WeatherData ParseJsonToWeatherData(Location location)
        {
            WebClient    client          = null;
            const string windDescription = "degree is ";

            try
            {
                client = new WebClient();
                string  json       = @client.DownloadString(UrlJsonAddress.ToString());
                JObject jsonObject = JObject.Parse(json);
                location.Initialize
                (
                    (string)jsonObject["location"]["name"],
                    double.Parse((string)jsonObject["location"]["lon"]),
                    double.Parse((string)jsonObject["location"]["lat"]),
                    (string)jsonObject["location"]["country"]
                );
                return(new WeatherData
                       (
                           location,
                           double.Parse((string)jsonObject["current"]["temp_c"]),
                           double.Parse((string)jsonObject["current"]["humidity"]),
                           double.Parse((string)jsonObject["current"]["pressure_mb"]),
                           ((string)jsonObject["current"]["condition"]["text"]).Remove(((string)jsonObject["current"]["condition"]["text"]).Length - 1),
                           (string)jsonObject["current"]["last_updated"],
                           double.Parse((string)jsonObject["current"]["wind_kph"]),
                           windDescription.Insert(windDescription.Length, (string)jsonObject["current"]["wind_degree"]),
                           (string)jsonObject["current"]["wind_dir"]
                       ));
            }
            catch (WebException)
            {
                throw new WeatherDataServiceException("Faild to connect to www.apixu.com");
            }
            catch (FormatException)
            {
                throw new WeatherDataServiceException("Failed to format the string to a number");
            }
            catch (Exception e)
            {
                throw new WeatherDataServiceException(e.Message);
            }
            finally
            {
                //Closing the connection to openweathermap.org
                client?.Dispose();

                //Restarting the address so next time we also get a correct url address
                UrlJsonAddress.Clear();
            }
        }
コード例 #47
0
 public void DownloadNext()
 {
     if (downloadQueue.Count > 0)
     {
         ThemeConfig theme = downloadQueue.Peek();
         client.DownloadFileAsync(new Uri(theme.imagesZipUri),
                                  theme.themeName + "_images.zip");
     }
     else
     {
         client?.Dispose();
         this.Close();
     }
 }
コード例 #48
0
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            ThemeLoader.taskbarHandle = IntPtr.Zero;
            wc?.Dispose();

            Task.Run(() =>
            {
                try
                {
                    File.Delete(imagesZipDest);
                }
                catch { }
            });
        }
コード例 #49
0
        protected virtual void Dispose(bool disposing)
        {
            if (IsDisposed)
            {
                return;
            }

            if (disposing)
            {
                _web?.Dispose();
            }

            IsDisposed = true;
        }
コード例 #50
0
 protected void Page_Load(object sender, EventArgs e)
 {
     string url = Request.QueryString["url"];
     Uri uri = new Uri(url);
     WebClient wc = new WebClient();
     wc.Encoding = System.Text.Encoding.UTF8;
     string content = wc.DownloadString(uri);
     //content = content.Replace("ruspo.ru", "volotour.ru");
     content = content.Replace("HotTours.aspx", "hot");
     content = content.Replace("href=\"/", "href=\"http://" + uri.Host + "/");
     content = content.Replace("src=\"/", "href=\"http://" + uri.Host + "/");
     Response.Write(content);
     wc.Dispose();
 }
コード例 #51
0
ファイル: FileDownload.cs プロジェクト: KirilToshev/Projects
 static void Main()
 {
     WebClient fileDownload = new WebClient();
     try
     {
         fileDownload.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "..\\..\\Logo-BASD-downloaded.jpg" );
     }
     catch (Exception exp)
     {
         Console.WriteLine(exp.Message);
     }
     finally
     {
         fileDownload.Dispose();
     }
 }
コード例 #52
0
        public void DownloadNext()
        {
            if (downloadQueue.Count > 0)
            {
                ThemeConfig   theme         = downloadQueue.Peek();
                List <string> imagesZipUris = theme.imagesZipUri.Split('|').ToList();

                client.DownloadFileAsync(new Uri(imagesZipUris.First()),
                                         theme.themeName + "_images.zip", imagesZipUris.Skip(1).ToList());
            }
            else
            {
                client?.Dispose();
                this.Close();
            }
        }
コード例 #53
0
        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            ThemeLoader.taskbarHandle = IntPtr.Zero;
            ThemeManager.downloadMode = false;
            wc?.Dispose();

            Task.Run(() =>
            {
                try
                {
                    System.Threading.Thread.Sleep(100);  // Wait for file to free up
                    File.Delete(themeZipDest);
                }
                catch { }
            });
        }
コード例 #54
0
    static void Main()
    {
        WebClient client = new WebClient();
        string remoteAddress = "";
        string fileName = "";

        try
        {
            Console.WriteLine("Enter the URI of the resource you want to download: ");
            remoteAddress = Console.ReadLine();

            // remoteAddress = "http://www.devbg.org/img/Logo-BASD.jpg";

            Uri uri = new Uri(remoteAddress);

            fileName = Path.GetFileName(uri.LocalPath);
            client.DownloadFile(uri, fileName);

            Console.WriteLine("File {0} was downloaded successfully.", fileName);
        }
        catch (ArgumentNullException)
        {
            Console.WriteLine("The address cannot be null.");
        }
        catch (ArgumentException)
        {
            Console.WriteLine("Path: {0} contains invalid characters.", remoteAddress);
        }
        catch (UriFormatException)
        {
            Console.WriteLine("{0} is invalid Uri format.", remoteAddress);
        }
        catch (WebException)
        {
            Console.WriteLine("The file at: {0} does not exists, or address is invalid.",
                remoteAddress);
        }
        catch (NotSupportedException)
        {
            Console.WriteLine("Method {0} has been called simultaneously on multiple threads.",
                "WebClient.DownloadFile");
        }
        finally
        {
            client.Dispose();
        }
    }
コード例 #55
0
ファイル: Main.cs プロジェクト: Lolwis111/BCS_Software
        private void ButtonInstall_Click(object sender, EventArgs e)
        {
            WebClient client = null;

            try
            {
                if (!Directory.Exists(_installPath))
                {
                    Directory.CreateDirectory(_installPath);
                }

                buttonCancel.Enabled  = false;
                buttonInstall.Enabled = false;
                buttonStart.Enabled   = false;

                if (File.Exists(_executablePath))
                {
                    File.Delete(_executablePath);
                }

                client = new WebClient();

                client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(Client_DownloadProgressChanged);
                client.DownloadFileCompleted   += new AsyncCompletedEventHandler(Client_DownloadFileCompleted);

                if (Environment.Is64BitOperatingSystem)
                {
                    client.DownloadFileAsync(new Uri("http://lolwis.bplaced.net/bcs/updates/BCS_Software64.exe"), _executablePath);
                }
                else
                {
                    client.DownloadFileAsync(new Uri("http://lolwis.bplaced.net/bcs/updates/BCS_Software32.exe"), _executablePath);
                }
            }
            catch (Exception ex)
            {
                StringBuilder builder = new StringBuilder();
                builder.AppendFormat("Fehler bei: {0}\n", ex.Source);
                builder.Append(ex.Message);

                MessageBox.Show(builder.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                client?.Dispose();
            }
        }
コード例 #56
0
ファイル: Backend.cs プロジェクト: kishoreven1729/WormFishing
    public static void PostHighScore(string name, long score)
    {
        try
        {
            WebClient   webClient = new WebClient();

            webClient.Headers.Add("Content-Type", "application/json");

            webClient.UploadStringAsync(_updateUri, "{ name : '" + name + "', score : " + score + " }");

            webClient.Dispose();
        }
        catch(System.Exception ex)
        {
            Debug.Log(ex.Message);
        }
    }
コード例 #57
0
    // Write a program that downloads a file from Internet (e.g. Ninja image) and stores it the current directory. Find in Google how
    // to download files in C#. Be sure to catch all exceptions and to free any used resources in the finally block.
    private static void Main()
    {
        Console.WriteLine("Enter the file (name and extension) to download");
        string file = Console.ReadLine();   // news-img01.png

        Console.WriteLine("Enter the address to that file");
        string URL = Console.ReadLine();    // http://telerikacademy.com/Content/Images/news-img01.png

        WebClient wc = new WebClient();
        try
        {
            wc.DownloadFile(URL, file);

            Console.Clear();
            Console.WriteLine("DONE");
            Console.WriteLine("(file is saved in the application's start directory)");
        }
        catch (ArgumentNullException ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("Try again!");
            Main();
        }
        catch (ArgumentException ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("Try again!");
            Main();
        }
        catch (WebException ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("Try again!");
            Main();
        }
        catch (NotSupportedException ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine("Try again!");
            Main();
        }
        finally
        {
            wc.Dispose();
        }
    }
コード例 #58
0
        private void Dispose(bool disposing)
        {
            if (_disposed)
            {
                return;
            }

            _webClient?.Dispose();
            _webClient = null;

            _stream?.Close();
            _stream = null;

            _streamReader?.Close();
            _streamReader = null;

            _disposed = true;
        }
コード例 #59
0
 static void Main()
 {
     using (WebClient webClient = new WebClient())
     {
         try
         {
             webClient.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", @"d:\Logo-BASD.jpg");
         }
         catch (Exception e)
         {
             Console.WriteLine("Exception : {0} : {1}", e.GetType().Name, e.Message);
         }
         finally
         {
             webClient.Dispose();
         }
     }
 }
コード例 #60
-1
 static void Main()
 {
     using (WebClient webCl = new WebClient())
     {
         try
         {
             Console.WriteLine("Write a program that downloads a file from Internet (e.g. http://www.devbg.org/img/Logo-BASD.jpg) and stores it the current directory. Find in Google how to download files in C#. Be sure to catch all exceptions and to free any used resources in the finally block.");
             Console.WriteLine();
             webCl.DownloadFile("http://www.devbg.org/img/Logo-BASD.jpg", "image.jpg");
             Console.WriteLine("Download Complete.");
         }
         catch (System.Net.WebException)
         {
             Console.WriteLine("Error downloading file.");
         }
         catch (System.ArgumentException)
         {
             Console.WriteLine("Wrong path");
         }
         finally
         {
             webCl.Dispose();
         }
     }
 }