【问题标题】:Download files and create the same folder structure as the Host下载文件并创建与主机相同的文件夹结构
【发布时间】:2013-04-09 20:05:41
【问题描述】:

我有一个配置文件,其中包含我要下载的 URI 列表。例如,

  http://xyz.abc.com/Dir1/Dir3/sds.txt
  http://xyz.abc.com/Dir2/Dir4/jhjs.txt
  http://xyz.abc.com/Dir1/itr.txt

我想读取配置文件并复制每个 URL,但同时创建与主机上相同的目录结构。例如,对于配置文件的第一行,我想在我的本地机器上创建目录结构 Dir1/Dir3(如果它不存在),然后将 sds.exe 复制到 .../Dir1/Dir3/

如何在 C# 中执行此操作?

我现在拥有的是:

string myStringWebResource; //Read this from the config file
System.IO.StreamReader file =
new System.IO.StreamReader("config.txt");

// Read the config file line by line
while ((myStringWebResource = file.ReadLine()) != null)
{
    // Create a new WebClient instance.
    using (WebClient myWebClient = new WebClient())
    {
        //How do I keep the original filename, e.g. sds.txt
        string outputFilename = @"" + ???";

        Console.WriteLine("Downloading ...");
        // Download the Web resource and save it into
        // the current filesystem folder.
        try
        {
            myWebClient.DownloadFile(myStringWebResource, outputFilename);
            Console.WriteLine("Successful");
        }
        catch (WebException e)
        {
            Console.WriteLine("Fail" + e.Message);
        }
    }  
}

虽然这让我可以下载配置文件中的所有文件,但

  1. 我遇到下载后必须命名的问题,如何保留它们的原始名称?
  2. 所有文件都下载到同一个文件夹中。如何从主机复制文件夹结构?

【问题讨论】:

    标签: c# file-io download directory


    【解决方案1】:

    我的建议是我们将主机过滤掉。然后拆分 / 上的每个剩余字符串。然后构建一个以 string[] 作为参数的方法来创建目录结构。使用原始路径(没有主机)在该目录中移动带有文件名(数组中的最后一项)的文件。

    如果主机是可变的,则删除第三个 / 之前的所有内容。

    【讨论】:

    • 很好。但是你能告诉我如何过滤掉主机
    猜你喜欢
    • 1970-01-01
    • 2018-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多