在while循环中下载文件C#

时间:2016-03-01 02:23:02

标签: c# winforms

我正在尝试将文件下载到用户计算机上的目录中。我首先删除了我不需要的所有文件,然后从网上的文件中获取文件,如下所示:

文件夹名称|文件名| DownloadLink

然而,它只下载第一个文件,循环正在运行。

class ModpackFileControl
{
    static string modpackDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "ImperialPVP");
    static string userDir = Properties.Settings.Default.userDir;

    public static void InstallUpdates()
    {
        //Delete Files
        ArrayList infoFiles = new ArrayList();
        infoFiles.Add("currentMods.txt");
        infoFiles.Add("previousMods.txt");
        infoFiles.Add("currentVersion.txt");
        infoFiles.Add("latestVersion.txt");
        infoFiles.Add("previousVersion.txt");
        infoFiles.Add("updateInfo.txt");          

        DirectoryInfo di = new DirectoryInfo(directory);
        foreach (FileInfo file in di.GetFiles())
        {
            if (!infoFiles.Contains(Convert.ToString(file)))
            {
                file.Delete();
            }

        }
        foreach (DirectoryInfo dir in di.GetDirectories())
        {
            dir.Delete(true);
        }

        //Download Files
        string modpackFilesText = Path.Combine(modpackDir, "modpackFiles.txt");

        WebClient webClient = new WebClient();
        webClient.DownloadFile("https://dl.dropbox.com/s/lqqvg2fdw9qb989/modpackFiles.txt?dl=0", modpackFilesText);

        StreamReader modpackFiles = File.OpenText(modpackFilesText);
        string line = modpackFiles.ReadLine();
        while (line != null)
        {
            string[] files = line.Split('|');

            string folder = files[0];
            string file = files[1];
            if (!Directory.Exists(Path.Combine(modpackDir, folder)))
            {
                Directory.CreateDirectory(Path.Combine(modpackDir, folder));
            }

            string downloadPath = Path.Combine(modpackDir, folder, file);
            string link = files[2];
            webClient.DownloadFile(link, downloadPath);
        }

        return;
    }
}

1 个答案:

答案 0 :(得分:1)

问题是你的while循环有条件line != null,但line仅在循环开始之前设置。

你可能想要这样的东西:

    string line = modpackFiles.ReadLine();
    while (line != null)
    {
     // your existing code here 
     line = modpackFiles.ReadLine();
    }