[英]Trying to download from a dynamic link with C#
我需要一些幫助來從未知的鏈接下載文件。 承認我們有這個網站www.website.com/fileX_Y.txt和X,Y是介於0到20之間的兩個整數。我嘗試了一下,我的代碼將繼續創建文件並將舊文件替換為空文件,因此我無法確定選出正確的 對不起,我的英語不好: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)
{
}
}
}
}
}
}
}
}
您的目標路徑導致沖突:
string path = "C:\\json\\" + x + y + ".txt";
如果x = 11並且y = 0,它將給出與x = 1和y = 10時相同的路徑。
更改它以在x和y之間添加定界符。
string path = "C:\\json\\" + x + "_" + y + ".txt";
我也是一個問題,因為您嘗試將相同文件最多進行20次。 沒有理由這樣做。
隨着文件名越來越相似,它正在被替換。 您可以按照此方法在文件名前追加日期時間,這樣,如果您的代碼再次運行,則也不會被替換。
string path = "C:\\json\\" + DateTime.Now.ToString("ddMMyyyy-HHmmss") + " " + x + "_" + y + ".txt";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.