Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.IO;
- using System.Net;
- namespace TestDownload
- {
- class Program
- {
- static string fileInProgress = string.Empty;
- static void Main(string[] args)
- {
- Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);
- List<string> fileurls = new List<string>();
- string[] files = Directory.GetFiles(@"E:\Edu\Books\Books");
- int count = 0;
- foreach (string filename in files)
- {
- FileInfo fn = new FileInfo(filename);
- count++;
- fileurls.Add("http://192.168.2.4/" + fn.Name);
- }
- foreach (string url in fileurls)
- {
- fileInProgress = url.Substring(url.LastIndexOf("/") + 1, (url.Length - url.LastIndexOf("/") - 1));
- DownloadFile(url, fileInProgress);
- }
- }
- static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
- {
- try
- {
- Console.ForegroundColor = ConsoleColor.Yellow;
- Console.WriteLine("Program interrupted..deleting corrupted file");
- Console.ResetColor();
- if (File.Exists(fileInProgress))
- {
- while (IsFileLocked(fileInProgress))
- {
- System.Threading.Thread.Sleep(1000);
- }
- File.Delete(fileInProgress);
- }
- }
- catch
- {
- Console.WriteLine("Error occured.");
- }
- }
- private static bool IsFileLocked(string fileName_in)
- {
- FileInfo inpFileInfo = new FileInfo(fileName_in);
- FileStream stream = null;
- try
- {
- stream = inpFileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
- }
- catch (IOException)
- {
- //the file is unavailable because it is:
- //still being written to
- //or being processed by another thread
- //or does not exist (has already been processed)
- return true;
- }
- finally
- {
- if (stream != null)
- stream.Close();
- }
- //file is not locked
- return false;
- }
- private static void DownloadFile(string url, string fileInProgress)
- {
- try
- {
- Console.WriteLine("Downloading " + fileInProgress);
- WebClient wb = new WebClient();
- wb.DownloadFile(new Uri(url), fileInProgress);
- }
- catch (WebException webexp)
- {
- if (File.Exists(fileInProgress))
- {
- File.Delete(fileInProgress);
- }
- Console.WriteLine("Error occured while downloading " + fileInProgress + "\n Msg -" + webexp.ToString());
- }
- catch (NotSupportedException nsExp)
- {
- if (File.Exists(fileInProgress))
- {
- File.Delete(fileInProgress);
- }
- Console.WriteLine("Error occured while downloading " + fileInProgress + "\n Msg -" + nsExp.ToString());
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment