【问题标题】:How do I get a list of files from a web directory?如何从 Web 目录中获取文件列表?
【发布时间】:2010-12-08 04:25:18
【问题描述】:

如何从 Web 目录中获取文件列表?如果我访问 Web 目录 URL,则 Internet 浏览器会列出该目录中的所有文件。现在我只想在 C# 中获取该列表并在 BITS(后台智能传输服务)中下载它们。

【问题讨论】:

    标签: c# microsoft-bits bits-service


    【解决方案1】:

    关于“在 C# 中获取该列表”部分:

    foreach (string filename in 
        Directory.GetFiles(
            Server.MapPath("/"), "*.jpg", 
            SearchOption.AllDirectories))
    {
        Response.Write(
            String.Format("{0}<br />", 
                Server.HtmlEncode(filename)));
    }
    

    【讨论】:

    • 感谢您的回复。这是创建列表的好方法,但我不想创建一个列表,我想读取和解析目录中的默认 IIS 文件列表。
    • @Eric,对不起,我不明白你想要完成什么;你能详细说明你的问题吗?
    • @NikolaLukic 它是来自System.Web 命名空间的一个类
    【解决方案2】:

    这是我最近研究的一个有趣的话题。如您所知,您可以通过 COM 访问 BITS,但这里有几个项目可以使其更容易:

    SharpBITS.NET
    Forms Designer Friendly Background Intelligent Transfer Service (BITS) wrapper

    这个article on MSDN 可能比你想知道的多一点。

    我对 CodeProject 链接中的代码进行了试验,它似乎运行良好。 CodePlex 项目看起来很不错,但我还没有尝试过。

    【讨论】:

    • 注意:我在我的项目中使用 SharpBITS.net。我同意似乎真的很好。
    【解决方案3】:

    好吧,如果 Web 服务器允许列出相关目录中的文件,那么您就可以开始了。

    不幸的是,对于网络服务器应该如何返回列表没有标准。它通常是 HTML,但 HTML 在多个 Web 服务器中的格式并不总是相同。

    如果您想始终从同一网络服务器上的同一目录下载文件,只需在网络浏览器的目录中执行“查看源代码”即可。然后尝试编写一个小的正则表达式,它将从 HTML 源中获取每个文件名。

    然后您可以创建一个 WebClient,请求目录 URL,解析响应以使用您的正则表达式获取文件名,然后使用您的 BITS 客户端处理文件

    希望对你有帮助

    【讨论】:

      【解决方案4】:
      private void ListFiles()
      {
      
          //get the user calling this page 
          Gaf.Bl.User userObj = base.User;
          //get he debug directory of this user
          string strDebugDir = userObj.UserSettings.DebugDir;
          //construct the Directory Info directory 
          DirectoryInfo di = new DirectoryInfo(strDebugDir);
          if (di.Exists == true)
          {
      
              //get the array of files for this 
              FileInfo[] rgFiles = di.GetFiles("*.html");
              //create the list ... .it is easier to sort ... 
              List<FileInfo> listFileInfo = new List<FileInfo>(rgFiles);
              //inline sort descending by file's full path 
              listFileInfo.Sort((x, y) => string.Compare(y.FullName, x.FullName));
              //now print the result 
              foreach (FileInfo fi in listFileInfo)
              {
                  Response.Write("<br><a href=" + fi.Name + ">" + fi.Name + "</a>");
              } //eof foreach
          } //eof if dir exists
      
      } //eof method 
      

      【讨论】:

        【解决方案5】:

        我编写了一些代码,可以从允许列表目录的 IIS 站点获取所有路径信息,包括文件和目录。您可以自定义正则表达式以满足您的需要(或更改为使用 html 解析器)。此外,您可以自己添加一些代码以获取更详细的信息,例如文件大小或创建时间。

        您可以在 2 行中获取所有路径信息:

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

        帮助代码:

        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:|https:)?(?<file>.*?)\"", RegexOptions.IgnoreCase);
                Regex regexDir = new Regex("dir.*?<a href=\"(http:|https:)?(?<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);
            }
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-08-07
          • 2013-06-15
          • 2020-09-11
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多