从http下载文件

时间:2016-01-22 02:34:23

标签: c# file http download

我正在尝试从http地址开始从开始日期到结束日期下载所有文件。我设法创建一个代码,获取名为“IMG_DK01IR1_yyyyMMddhhmm_004.bz2”的文件。问题是日期部分只查看dt_DLTime(201512180215),但我希望dt_DLTime中的所有文件都是dt。我怎样才能做到这一点?这是我的代码:

            DownloadLatestData();
        }

        void Button1Click(object sender, EventArgs e)
        {
            Application.Exit();
        }


        public void DownloadLatestData()
        {

            DateTime dt = DateTime.UtcNow;

            DateTime dt_DLTime = dt.Add(new TimeSpan(-35,0,-15,0));

            String m_DLTime = dt_DLTime.ToString("yyyyMMddhhmm");


            textBox1.AppendText("Downloading for " + m_DLTime + "UTC" + Environment.NewLine);

            // create download string for JMV
            String m_DLStr_JMV_1 = "http://automet.fugrogeos.com:9090/pub/singapore";
            String m_DLStr_JMV = String.Concat(m_DLStr_JMV_1, "/IMG_DK01IR1_", m_DLTime, "_004.bz2");      
            String m_LocalFN_JMV = String.Concat(Application.StartupPath + "\\jmv\\IMG_DK01IR1_", m_DLTime, "_004.bz2");


            WebClient webClient = new WebClient();
            try
            {
                webClient.DownloadFile(m_DLStr_JMV, m_LocalFN_JMV);
            }
            catch (Exception e)
            {
                // write a line of text to the file
                textBox1.AppendText(e.ToString() + Environment.NewLine);
            }

            textBox1.AppendText("Finish downloading." + Environment.NewLine);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

这是一种略有不同的方法。以下代码将尝试识别文件夹中的所有文件链接,然后将其下载到您的硬盘。

一旦你知道了所有文件名,就应该很容易按日期时间过滤(如果需要的话)。

使用此代码替换DownloadLatestData()方法的代码。我认为您的网络服务器无法公开访问。所以代码没有经过测试。

       var webClient = new WebClient();
       const string baseUrl = @"http://automet.fugrogeos.com:9090/pub/singapore";
       const string diskPath = @"c:\MyFiles\";
       string content = webClient.DownloadString(baseUrl);
       var htmlLinks = content.Split(new[] {"</A>"}, StringSplitOptions.RemoveEmptyEntries);
       var paths = new List<string>();
       foreach (var htmlLink in htmlLinks)
       {
           var linkHrefs = htmlLink.Split(new[] { @"<A HREF=" }, StringSplitOptions.RemoveEmptyEntries);
           foreach (var linkHref in linkHrefs.Where(h => h.ToLower().Contains(".bz2"))) 
           {
               var fileRefs = linkHref.Split(new[] {">"}, StringSplitOptions.RemoveEmptyEntries);
               paths.Add(fileRefs[fileRefs.Length - 1]);
           }
       }

       foreach (var path in paths)
       {
          var bytes =  webClient.DownloadData(new Uri(baseUrl + path));
          File.WriteAllBytes(diskPath+ path, bytes);
       }