2008-09-23 4 views

답변

27

몇 가지 중요한 고려 사항 :

  1. HTTP 서버가 원하는 디렉토리에 대한 디렉토리 목록을 허용하도록 구성되어야한다;
  2. 디렉토리 목록은 일반적인 HTML 페이지이므로 디렉토리 목록의 형식을 정의하는 표준은 없습니다.
  3. 고려 사항으로 인해 은 각 서버에 대한 특정 코드를 입력해야하는 곳입니다.

정규식을 선택하는 것이 좋습니다. 이렇게하면 신속한 파싱 및 사용자 정의가 가능합니다. 사이트 당 특정 정규식 패턴을 얻을 수 있으며 매우 모듈 방식으로 접근 할 수 있습니다. 소스 코드를 변경하지 않고 새 사이트 지원으로 구문 분석 모듈을 향상시키려는 경우 정규 표현식 패턴에 URL을 매핑하는 데 외부 소스를 사용하십시오.

예는 양자 택일 WebDAV의 서버를 설정할 수 있습니다 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(); 
     } 
    } 
} 
8

에 대한 기본적인 이해 :

디렉토리 목록은 웹 서버에 의해 생성 된 단지 HTML 페이지입니다. 웹 서버가 이러한 디렉토리를 나열하는 표준 방법이 없기 때문에 각 웹 서버는 이러한 방식으로 이러한 HTML 페이지를 생성합니다.

디렉토리 목록을 얻는 가장 좋은 방법은 디렉토리 목록을 표시하려는 URL에 대한 HTTP 요청을 수행하고 반환 된 HTML에서 모든 링크를 구문 분석하고 추출하는 것입니다.

HTML 링크를 구문 분석하려면 HTML Agility Pack을 사용해보십시오.

디렉터리 검색 :

디렉터리 검색이 디렉토리에있는 파일의 HTML 표현을 얻을 켜져 있어야합니다에서 당신이 디렉토리를 나열하고 싶은 웹 서버. 따라서 HTTP 서버가 원할 경우에만 디렉토리 목록을 얻을 수 있습니다.

되는 HTML 민첩성 팩의 빠른 예 :

HtmlDocument doc = new HtmlDocument(); 
doc.Load(strURL); 
foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//[email protected]") 
{ 
HtmlAttribute att = link"href"; 
//do something with att.Value; 
} 

대안 클리너 : 그것은 당신의 상황에서 가능하다면

는 깨끗한 방법은 디렉토리에 대한 의도 된 프로토콜을 사용하는 것입니다 FTP (File Transfer Protocol), SFTP (SSH를 통한 FTP) 또는 FTPS (SSL을 통한 FTP)와 같은 목록입니다. 디렉터리 검색이 켜져 있지 않은 경우

은 무엇 : 웹 서버가 디렉터리 검색이 설정되어 있지 않은 경우

, 다음 디렉토리 목록을 얻을 수있는 쉬운 방법이 없습니다.

이 경우 할 수있는 최선의 방법은 주어진 URL에서 시작하여 같은 페이지의 모든 HTML 링크를 따르고이 HTML에있는 리소스의 상대 경로를 기반으로 직접 디렉토리의 가상 목록을 작성하는 것입니다 페이지. 이것은 웹 서버에 실제로 어떤 파일이 있는지에 대한 전체 목록을 제공하지는 않습니다.

0

원하는 특정 디렉토리에 디렉토리 목록이 설정되어 있고 기본 파일이없는 경우 (일반적으로 index.htm, index.html 또는 default.html이지만 항상 구성 가능)는 불가능합니다. 그래야만 디렉토리 목록을 볼 수 있습니다. 디렉토리 목록은 일반적으로 HTML로 마크 업되고 구문 분석이 필요합니다.코드 이전

0

에서 디렉토리 목록을 인쇄합니다.

2

위대한 게시자 주셔서 감사합니다. 나를 위해 아래의 패턴이 잘 작동했습니다.

<AHREF=\\"\S+\">(?<name>\S+)</A> 

또한 http://regexhero.net/tester에서 테스트했습니다.

GetDirectoryListingRegexForUrl 방법에, 나는

<AHREF=\\"\S+\">(?<name>\S+)</A>

nstance의 패턴에있는 백 슬래시와 큰 따옴표 전에() 더 백 슬래시를 추가하기 위해 C# 코드에서 그것을, 당신이 사용하는 이

반환 같은 것을 사용한다 "< A HREF = \\"\ S + \\ "> (? \ S +)";

건배!

+0

고맙습니다. 그것은 시간을 절약했습니다. –

4

난 그냥 위의 수정 및 발견이 최선의

public static class GetallFilesFromHttp 
{ 
    public static string GetDirectoryListingRegexForUrl(string url) 
    { 
     if (url.Equals("http://ServerDirPath/")) 
     { 
      return "\\\"([^\"]*)\\\""; 
     } 
     throw new NotSupportedException(); 
    } 
    public static void ListDiractory() 
    { 
     string url = "http://ServerDirPath/"; 
     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.ToString()); 
         } 
        } 
       } 
      } 
      Console.ReadLine(); 
     } 
    } 
} 
1

내가 FTP 서버에 액세스 할 수 없을 때 다음 코드는 나를 위해 잘 작동 : 그러나

public static string[] GetFiles(string url) 
{ 
    List<string> files = new List<string>(500); 
    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("<a href=\".*\">(?<name>.*)</a>"); 
      MatchCollection matches = regex.Matches(html); 

      if (matches.Count > 0) 
      { 
       foreach (Match match in matches) 
       { 
        if (match.Success) 
        { 
         string[] matchData = match.Groups[0].ToString().Split('\"'); 
         files.Add(matchData[1]); 
        } 
       } 
      } 
     } 
    } 
    return files.ToArray(); 
} 

을 때 ftp 서버에 액세스 할 수 있으므로 다음 코드가 훨씬 빠르게 작동합니다.

public static string[] getFtpFolderItems(string ftpURL) 
{ 
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL); 
    request.Method = WebRequestMethods.Ftp.ListDirectory; 

    //You could add Credentials, if needed 
    //request.Credentials = new NetworkCredential("anonymous", "password"); 

    FtpWebResponse response = (FtpWebResponse)request.GetResponse(); 

    Stream responseStream = response.GetResponseStream(); 
    StreamReader reader = new StreamReader(responseStream); 

    return reader.ReadToEnd().Split("\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); 
} 
관련 문제