Adam Ladhari
Adam Ladhari

Reputation: 1

Trying to download from a dynamic link with C#

I need some help to download a file from a link that is half unknown. Admitting we have this website www.website.com/fileX_Y.txt and X , Y are two int between 0 and 20. I gave it a try and my code will keep creating files and replacing older one by a empty one so I cant figure out the correct one. Sorry for my bad english :D ''

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.ComponentModel;
using System.Threading.Tasks;

namespace ConsoleApp13
{
    class Program
    {
        static void Main(string[] args)
        {
            for (int i = 0; i < 20; i++)
            {
                for (int x = 0; x < 20; x++)
                {
                    for (int y = 0; y < 20; y++)
                    {
                        string uri = "lieen" + x + "_ " + y + ".extension";
                        string path = "C:\\json\\" + x + y + ".txt";
                        WebClient client = new WebClient();
                        try
                        {
                            client.DownloadFile(uri, path);
                        }
                        catch (WebException wex)
                        {
                            if (((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.NotFound)
                            {

                            }
                        }
                    }

                }
            }
        }
    }
}

Upvotes: 0

Views: 67

Answers (2)

Karan
Karan

Reputation: 12629

As file names are getting similar it is getting replaced. You can follow this approach as append Date Time before file name so if your code run again then also it will not get replaced.

string path = "C:\\json\\" + DateTime.Now.ToString("ddMMyyyy-HHmmss") + " " + x + "_" + y + ".txt";

Upvotes: 0

Ctznkane525
Ctznkane525

Reputation: 7465

Your destination path is causing collisions:

string path = "C:\\json\\" + x + y + ".txt";

if x = 11 and y = 0, it will give the same path as when x = 1 and y = 10.

Change it to add a delimiter between x and y.

string path = "C:\\json\\" + x + "_" + y + ".txt";

The i is also a problem because you are trying the same files up to 20 times. No reason to do that.

Upvotes: 3

Related Questions