小编典典

C#HttpWebRequest命令获取目录列表

c#

关闭。 此问题不符合堆栈溢出准则。它当前不接受答案。


想改善这个问题吗? 更新问题,使其成为Stack Overflow
的主题

2年前关闭。

我需要一个简短的代码片段来从HTTP服务器获取目录列表。

谢谢


阅读 797

收藏
2020-05-19

共1个答案

小编典典

代码之前的一些重要注意事项:

  1. 必须将HTTP Server配置为允许列出所需目录的目录。
  2. 因为目录列表是普通的HTML页面,所以没有标准来定义目录列表的格式。
  3. 由于考虑因素 2 ,您需要为每台服务器放置特定的代码。

我的选择是使用正则表达式。这允许快速解析和自定义。您可以在每个站点上获得特定的正则表达式模式,从而可以采用一种非常模块化的方法。如果您计划在不更改源代码的情况下使用新的站点支持来增强解析模块,请使用外部源将URL映射到正则表达式模式。

http://www.ibiblio.org/pub/打印目录列表的示例

namespace Example
{
    using System;
    using System.Net;
    using System.IO;
    using System.Text.RegularExpressions;

    public class MyExample
    {
        public static string GetDirectoryListingRegexForUrl(string url)
        {
            if (url.Equals("http://www.ibiblio.org/pub/"))
            {
                return "<a href=\".*\">(?<name>.*)</a>";
            }
            throw new NotSupportedException();
        }
        public static void Main(String[] args)
        {
            string url = "http://www.ibiblio.org/pub/";
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream()))
                {
                    string html = reader.ReadToEnd();
                    Regex regex = new Regex(GetDirectoryListingRegexForUrl(url));
                    MatchCollection matches = regex.Matches(html);
                    if (matches.Count > 0)
                    {
                        foreach (Match match in matches)
                        {
                            if (match.Success)
                            {
                                Console.WriteLine(match.Groups["name"]);
                            }
                        }
                    }
                }
            }

            Console.ReadLine();
        }
    }
}
2020-05-19