【问题标题】:List all files from a URL in a Console Application列出控制台应用程序中 URL 中的所有文件
【发布时间】:2018-06-26 15:17:00
【问题描述】:

我正在尝试获取位于 URL 中的所有文件。 当您在浏览器中访问 URL 时,会列出所有文件,所以我想我也可以在控制台程序中打印这些文件。

显然,我下面的代码不起作用并抛出 System.ArgumentException "URI formats are not supported." 。或者真的可以在使用 C# 的控制台应用程序中实现这一点吗?

class Program
{
    public static void Main(string[] args)
    {
        foreach (string filename in Directory.GetFiles(@"http://mywebsite.files/", "*.*"))
        {
            Console.WriteLine(filename);
        }

        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

【问题讨论】:

  • 你需要解析你的web服务器返回的HTML(你可以使用HTML Agility Pack

标签: c# console-application


【解决方案1】:

您不能使用Directory 类来列出 Web 目录的文件,而且必须将服务器配置为允许目录/文件列出

你应该做的是一个返回文件列表的网络请求。

查看here 了解更多信息

【讨论】:

    【解决方案2】:

    也许您应该阅读 ftp 协议的用法。您尝试解决问题的方法很可能行不通。

    【讨论】:

      【解决方案3】:

      如果您有 FTP 访问权限,则可以使用 FtpWebRequest 类。这是来自http://msdn.microsoft.com/en-us/library/ms229716.aspx的示例

      public class WebRequestGetExample
      {
          public static void Main ()
          {
              // Get the object used to communicate with the server.
              FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/");
              request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
      
              // This example assumes the FTP site uses anonymous logon.
              request.Credentials = new NetworkCredential ("anonymous","janeDoe@contoso.com");
      
              FtpWebResponse response = (FtpWebResponse)request.GetResponse();
      
              Stream responseStream = response.GetResponseStream();
              StreamReader reader = new StreamReader(responseStream);
              Console.WriteLine(reader.ReadToEnd());
      
              Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);
      
              reader.Close();
              response.Close();
          }
      }
      

      【讨论】:

        【解决方案4】:

        我写了一些代码,可以获取IIS http站点下的所有Path Info,如果它允许目录列表,最后你可以这样做:

        List<PathInfo> pathInfos = new List<PathInfo>();
        HttpHelper.GetAllFilePathAndSubDirectory("http://localhost:33333/", pathInfos);
        HttpHelper.PrintAllPathInfo(pathInfos);
        

        帮助代码,正则表达式可以自己定制,或者改用html解析器):

        public static class HttpHelper
        {
            public static string ReadHtmlContentFromUrl(string url)
            {
                string html = string.Empty;
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    html = reader.ReadToEnd();
                }
                //Console.WriteLine(html);
                return html;
            }
        
            public static void GetAllFilePathAndSubDirectory(string baseUrl, List<PathInfo> pathInfos)
            {
                Uri baseUri = new Uri( baseUrl.TrimEnd('/') );
                string rootUrl = baseUri.GetLeftPart(UriPartial.Authority);
        
                Regex regexFile = new Regex("[0-9] <a href=\"(http:)?(?<file>.*?)\"", RegexOptions.IgnoreCase);
                Regex regexDir = new Regex("dir.*?<a href=\"(http:)?(?<dir>.*?)\"", RegexOptions.IgnoreCase);
        
                string html = ReadHtmlContentFromUrl(baseUrl);
                //Files
                MatchCollection matchesFile = regexFile.Matches(html);
                if (matchesFile.Count != 0)
                    foreach (Match match in matchesFile)
                        if (match.Success)
                            pathInfos.Add(
                                new PathInfo( rootUrl + match.Groups["file"], false));
                //Dir
                MatchCollection matchesDir = regexDir.Matches(html);
                if (matchesDir.Count != 0)
                    foreach (Match match in matchesDir)
                        if (match.Success)
                        {
                            var dirInfo = new PathInfo(rootUrl + match.Groups["dir"], true);
                            GetAllFilePathAndSubDirectory(dirInfo.AbsoluteUrlStr, dirInfo.Childs);
                            pathInfos.Add(dirInfo);
                        }                        
        
            }
        
        
            public static void PrintAllPathInfo(List<PathInfo> pathInfos)
            {
                pathInfos.ForEach(f =>
                {
                    Console.WriteLine(f.AbsoluteUrlStr);
                    PrintAllPathInfo(f.Childs);
                });
            }
        
        }
        
        
        
        public class PathInfo
        {
            public PathInfo(string absoluteUri, bool isDir)
            {
                AbsoluteUrl = new Uri(absoluteUri);
                IsDir = isDir;
                Childs = new List<PathInfo>();
            }
        
            public Uri AbsoluteUrl { get; set; }
        
            public string AbsoluteUrlStr
            {
                get { return AbsoluteUrl.ToString(); }
            }
        
            public string RootUrl
            {
                get { return AbsoluteUrl.GetLeftPart(UriPartial.Authority); }
            }
        
            public string RelativeUrl
            {
                get { return AbsoluteUrl.PathAndQuery; }
            }
        
            public string Query
            {
                get { return AbsoluteUrl.Query; }
            }
        
            public bool IsDir { get; set; }
            public List<PathInfo> Childs { get; set; }
        
        
            public override string ToString()
            {
                return String.Format("{0} IsDir {1} ChildCount {2} AbsUrl {3}", RelativeUrl, IsDir, Childs.Count, AbsoluteUrlStr);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 2018-08-01
          • 2012-04-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多