locked
How can I download images from a website each 15 minutes to a directory with datetime.now in the name of the directories ? RRS feed

  • Question

  • using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace WeatherInfo
    {
    	public partial class Form1 : Form
    	{
    		private Queue<string> _downloadUrls = new Queue<string>();
    		private WebClient Client = new WebClient();
    		private List<string> urls = new List<string>();
    		private string fname;
    		string appDataPath;
    		string radarPath = "RadarImage";
    		string radarFileName = "Radar";
    		Uri radarUri;
    		string radarImageWebAddressP1;
    		string radarImageWebAddressP2;
    		string folderName = "";
    
    		public Form1()
    		{
    			InitializeComponent();
    
    			appDataPath = Path.GetDirectoryName(Application.LocalUserAppDataPath);
    			radarPath = Path.Combine(appDataPath, radarPath);
    			if (!Directory.Exists(radarPath))
    				Directory.CreateDirectory(radarPath);
    
    			radarImageWebAddressP1 = "http://www.ims.gov.il/Ims/Pages/RadarImage.aspx?Row=";
    			radarImageWebAddressP2 = "&TotalImages=10&LangID=1&Location=";
    
    			for (int i = 0; i < 9; i++)
    			{
    				urls.Add(radarImageWebAddressP1 + i + radarImageWebAddressP2);
    			}
    		}
    
    		private void downloadFile(IEnumerable<string> urls)
    		{
    			foreach (var url in urls)
    			{
    				_downloadUrls.Enqueue(url);
    			}
    
    			// Starts the download
    			btnGetDownload.Text = "Downloading...";
    			btnGetDownload.Enabled = false;
    			progressBar1.Visible = true;
    			lblFileName.Visible = true;
    
    			DownloadFile();
    		}
    
    		int counter = 0;
    		private void DownloadFile()
    		{
    			if (_downloadUrls.Any())
    			{
    				WebClient client = new WebClient();
    				client.DownloadProgressChanged += client_DownloadProgressChanged;
    				client.DownloadFileCompleted += client_DownloadFileCompleted;
    
    				var url = _downloadUrls.Dequeue();
    				fname = Path.Combine(folderName, radarFileName + counter + ".gif");
    				client.DownloadFileAsync(new Uri(url), fname);
    				lblFileName.Text = url;
    				return;
    			}
    			else
    			{
    				timer1.Enabled = false;
    			}
    
    			// End of the download
    			btnGetDownload.Text = "Download Complete";
    		}
    
    		private void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
    		{
    			if (e.Error != null)
    			{
    				// handle error scenario
    				throw e.Error;
    			}
    			else
    			{
    				counter++;
    				pictureBox1.Load(fname);
    			}
    			if (e.Cancelled)
    			{
    				// handle cancelled scenario
    			}
    			DownloadFile();
    		}
    
    		void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
    		{
    			double bytesIn = double.Parse(e.BytesReceived.ToString());
    			double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
    			double percentage = bytesIn / totalBytes * 100;
    			progressBar1.Value = int.Parse(Math.Truncate(percentage).ToString());
    		}
    
    		private void Form1_Load(object sender, EventArgs e)
    		{
    
    		}
    
    		private void button1_Click(object sender, EventArgs e)
    		{
    			timer1.Enabled = true;
    		}
    
    		private void pictureBox1_Click(object sender, EventArgs e)
    		{
    			RadarForm rf = new RadarForm();
    			rf.PictureBox(pictureBox1);
    			rf.Show();
    		}
    
    		private void timer1_Tick(object sender, EventArgs e)
    		{
    			string date = DateTime.Now.ToString("ddd MM.dd.yyyy");
    			string time = DateTime.Now.ToString("HH.mm tt");
    			string format = "on {0} At {1}";
    			folderName = string.Format(format, date, time);
    			folderName = Path.Combine(radarPath, folderName);
    
    			if (!Directory.Exists(folderName))
    				Directory.CreateDirectory(folderName);
    
    			downloadFile(urls);
    		}
    	}
    }

    Should be simple I guess.

    What I want to do is when running the application it will find the time have been passed from the current datetime.now and the last created directory with datetime.now in it's name.

    If 15 or more minutes have been passed make a first time download and then make a download each 15 minutes.

    If there is no yet any directories with datetime.now in the name and if there is a directory but it's empty also make a first time download then each 15 minutes.

    What I'm trying now is just to make a test so I added a button to start the download but once it' creating a directory with datetime.now in it's name the next time it's trying to download a image I'm getting exception the file is busy.

    System.Reflection.TargetInvocationException: 'Exception has been thrown by the target of an invocation.'

    IOException: The process cannot access the file 'C:\Users\test\AppData\Local\WeatherInfo\WeatherInfo\RadarImage\on Fri 10.12.2018 At 13.47 PM\Radar0.gif' because it is being used by another process.


    Friday, October 12, 2018 10:48 AM

All replies

  • If I'm moving out the code in the timer1_Tick to another method:

    private void dl()
    		{
    			string date = DateTime.Now.ToString("ddd MM.dd.yyyy");
    			string time = DateTime.Now.ToString("HH.mm tt");
    			string format = "on {0} At {1}";
    			folderName = string.Format(format, date, time);
    			folderName = Path.Combine(radarPath, folderName);
    
    			if (!Directory.Exists(folderName))
    				Directory.CreateDirectory(folderName);
    
    			downloadFile(urls);
    		}

    And will call this method from the constructor without starting the timer it will download the images fine.

    But I want to use the timer but not to download each a second (The interval is set to 1000) but to download each 15 minutes like i described above.

    Friday, October 12, 2018 10:57 AM
  • Hello,

    > but not to download each a second (The interval is set to 1000) but to download each 15 minutes like i described above

    And what stop you to set an Interval for 15 Minutes?  15 * 60 * 1000? 

    -----

    In your code are one problem - 

    folderName = string.Format(format, date, time);
    - would not work as expected.


    Sincerely, Highly skilled coding monkey.

    Friday, October 12, 2018 11:23 AM
  • P.S. I also would look on BackgroundWorker - it more suitable to run a task which suppose to run in the background.

    Sincerely, Highly skilled coding monkey.

    Friday, October 12, 2018 11:25 AM