2016-01-22 88 views
-1

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

  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); 
     } 
    } 
} 
+0

如果我理解正确的话,你想从给定的开局'yyyyMMddhhmm'格式日期时间字符串列表给定的结束日期,然后使用该列表来生成的网址下载 – Russ

回答

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); 
     }