简体   繁体   English

尝试使用C#从动态链接下载

[英]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. 承认我们有这个网站www.website.com/fileX_Y.txt和X,Y是介于0到20之间的两个整数。我尝试了一下,我的代码将继续创建文件并将旧文件替换为空文件,因此我无法确定选出正确的 Sorry for my bad english :D '' 对不起,我的英语不好: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)
                            {

                            }
                        }
                    }

                }
            }
        }
    }
}

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. 如果x = 11并且y = 0,它将给出与x = 1和y = 10时相同的路径。

Change it to add a delimiter between x and y. 更改它以在x和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. 我也是一个问题,因为您尝试将相同文件最多进行20次。 No reason to do that. 没有理由这样做。

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";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM