使用C#FtpWebRequest列出服务器文件夹和子文件夹 [英] Listing server folders and sub folders using C# FtpWebRequest

查看:85
本文介绍了使用C#FtpWebRequest列出服务器文件夹和子文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 StreamReader 在树状视图上获取文件,目录和子目录的完整列表.问题是花费的时间太长,并引发*操作超时异常",并且仅显示一个级别.

I am trying to get full list of files, directories and sub-directories on tree view using StreamReader. The problem is it took too long and throws *"Operation time out exception" and shows only one level.

这是我的代码

public void getServerSubfolder(TreeNode tv, string parentNode) {
  string ptNode;
  List<string> files = new List<string> ();
  try { 
    FtpWebRequest request = (FtpWebRequest) WebRequest.
    Create(parentNode);
    request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;

    request.Credentials = new NetworkCredential(this.userName, this.Password);
    request.UseBinary = true;
    request.UsePassive = true;
    request.Timeout = 10000;
    request.ReadWriteTimeout = 10000;
    request.KeepAlive = false;
    FtpWebResponse response = (FtpWebResponse) request.GetResponse();
    Stream responseStream = response.GetResponseStream();
    StreamReader reader = new StreamReader(responseStream);
    string fileList;
    string[] fileName;
    //MessageBox.Show(reader.ReadToEnd().ToString());
    while (!reader.EndOfStream) {
      fileList = reader.ReadLine();
      fileName = fileList.Split(' ');
      if (fileName[0] == "drwxr-xr-x") {
        // if it is directory
        TreeNode tnS = new TreeNode(fileName[fileName.Length - 1]);
        tv.Nodes.Add(tnS);
        ptNode = parentNode + "/" + fileName[fileName.Length - 1] + "/";
        getServerSubfolder(tnS, ptNode);
      } else files.Add(fileName[fileName.Length - 1]);
    }
    reader.Close();
    response.Close();
  } catch (Exception ex) {
    MessageBox.Show("Sub--here " + ex.Message + "----" + ex.StackTrace);
  }
}

推荐答案

我正在做类似的事情,但是我没有使用StreamReader.ReadLine()来使用每个对象,而是使用StreamReader.ReadToEnd()一次获得了所有内容.您不需要ReadLine()即可获取目录列表.下面是我的完整代码(教程):

I'm doing similar things, but instead of using StreamReader.ReadLine() for each one, I get it all at once with StreamReader.ReadToEnd(). You don't need ReadLine() to just get a list of directories. Below is my entire code (Entire howto is explained in this tutorial):

        FtpWebRequest request=(FtpWebRequest)FtpWebRequest.Create(path);
        request.Method=WebRequestMethods.Ftp.ListDirectoryDetails;
        List<ftpinfo> files=new List<ftpinfo>();

        //request.Proxy = System.Net.WebProxy.GetDefaultProxy();
        //request.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        request.Credentials = new NetworkCredential(_username, _password);
        Stream rs=(Stream)request.GetResponse().GetResponseStream();

        OnStatusChange("CONNECTED: " + path, 0, 0);

        StreamReader sr = new StreamReader(rs);
        string strList = sr.ReadToEnd();
        string[] lines=null;

        if (strList.Contains("\r\n"))
        {
            lines=strList.Split(new string[] {"\r\n"},StringSplitOptions.None);
        }
        else if (strList.Contains("\n"))
        {
            lines=strList.Split(new string[] {"\n"},StringSplitOptions.None);
        }

        //now decode this string array

        if (lines==null || lines.Length == 0)
            return null;

        foreach(string line in lines)
        {
            if (line.Length==0)
                continue;
            //parse line
            Match m= GetMatchingRegex(line);
            if (m==null) {
                //failed
                throw new ApplicationException("Unable to parse line: " + line);
            }

            ftpinfo item=new ftpinfo();
            item.filename = m.Groups["name"].Value.Trim('\r');
            item.path = path;
            item.size = Convert.ToInt64(m.Groups["size"].Value);
            item.permission = m.Groups["permission"].Value;
            string _dir = m.Groups["dir"].Value;
            if(_dir.Length>0  && _dir != "-")
            {
                item.fileType = directoryEntryTypes.directory;
            } 
            else
            {
                item.fileType = directoryEntryTypes.file;
            }

            try
            {
                item.fileDateTime = DateTime.Parse(m.Groups["timestamp"].Value);
            }
            catch
            {
                item.fileDateTime = DateTime.MinValue; //null;
            }

            files.Add(item);
        }

        return files;

这篇关于使用C#FtpWebRequest列出服务器文件夹和子文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆