当成功连接到ftp服务器时,如何检查并通知用户?

时间:2014-12-10 10:15:29

标签: c# .net winforms ftp

在这个button2点击事件中,我正在启动一个后台工作,它将从我的ftp服务器中检索所有目录和文件,并将在treeView上实时显示它们。

private void button2_Click(object sender, EventArgs e)
        {
            label13.Text = "Retrieving ftp content please wait";
            button2.Enabled = false;
            button3.Enabled = false;
            toolStripProgressBar2.Visible = true;
            backgroundWorker1.RunWorkerAsync(txtHost.Text);
        }

在backgoundworker1做了我做的工作事件:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            var root = Convert.ToString(e.Argument);  // txtHost.Text;

            searched_until_now_dirs = 0;
            total_dirs = 1;
            max_percentage = 0;
            last_update = DateTime.Now;
            directories_real_time = new TreeNode();
            var dirNode = CreateDirectoryNode(root, "root",1);

            e.Result = dirNode;
        }

方法CreateDirectoryNode

private int total_dirs;
        private int searched_until_now_dirs;
        private int max_percentage;
        private TreeNode directories_real_time;
        private string SummaryText;

        private TreeNode CreateDirectoryNode(string path, string name , int recursive_levl )
        {
            var directoryNode = new TreeNode(name);
            var directoryListing = GetDirectoryListing(path);

        }

和GetDirectoryListing:

public IEnumerable<FTPListDetail> GetDirectoryListing(string rootUri)
        {
            var CurrentRemoteDirectory = rootUri;
            var result = new StringBuilder();
            var request = GetWebRequest(WebRequestMethods.Ftp.ListDirectoryDetails, CurrentRemoteDirectory);
            using (var response = request.GetResponse())
            {
                using (var reader = new StreamReader(response.GetResponseStream()))
                {
                    string line = reader.ReadLine();
                    while (line != null)
                    {
                        result.Append(line);
                        result.Append("\n");
                        line = reader.ReadLine();
                    }
                    if (string.IsNullOrEmpty(result.ToString()))
                    {
                        return new List<FTPListDetail>();
                    }
                    result.Remove(result.ToString().LastIndexOf("\n"), 1);
                    var results = result.ToString().Split('\n');
                    string regex =
                        @"^" +               //# Start of line
                        @"(?<dir>[\-ld])" +          //# File size          
                        @"(?<permission>[\-rwx]{9})" +            //# Whitespace          \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<filecode>\d+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<owner>\w+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<group>\w+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<size>\d+)" +
                        @"\s+" +            //# Whitespace          \n
                        @"(?<month>\w{3})" +          //# Month (3 letters)   \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<day>\d{1,2})" +        //# Day (1 or 2 digits) \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<timeyear>[\d:]{4,5})" +     //# Time or year        \n
                        @"\s+" +            //# Whitespace          \n
                        @"(?<filename>(.*))" +            //# Filename            \n
                        @"$";                //# End of line

                    var myresult = new List<FTPListDetail>();
                    foreach (var parsed in results)
                    {
                        var split = new Regex(regex)
                            .Match(parsed);
                        var dir = split.Groups["dir"].ToString();
                        var permission = split.Groups["permission"].ToString();
                        var filecode = split.Groups["filecode"].ToString();
                        var owner = split.Groups["owner"].ToString();
                        var group = split.Groups["group"].ToString();
                        var filename = split.Groups["filename"].ToString();
                        var size = split.Groups["size"].Length;
                        myresult.Add(new FTPListDetail()
                        {
                            Dir = dir,
                            Filecode = filecode,
                            Group = group,
                            FullPath = CurrentRemoteDirectory + "/" + filename,
                            Name = filename,
                            Owner = owner,
                            Permission = permission,
                        });
                    };
                    return myresult;
                }
            }
        }

最后我在做ftp请求:

private FtpWebRequest GetWebRequest(string method, string uri)
        {
            Uri serverUri = new Uri("ftp://"+ uri);
            if (serverUri.Scheme != Uri.UriSchemeFtp)
            {
                return null;
            }
            var reqFTP = (FtpWebRequest)FtpWebRequest.Create(serverUri);
            reqFTP.Method = method;
            reqFTP.UseBinary = true;
            reqFTP.Credentials = new NetworkCredential(txtUsername.Text, txtPassword.Text);
            reqFTP.Proxy = null;
            reqFTP.KeepAlive = false;
            reqFTP.UsePassive = false;
            return reqFTP;
        }

当我点击按钮并启动后台工作时,它需要几秒钟,直到它开始检索目录和文件并在treeView上显示它们。

我现在要做的是以某种方式在GetwebRequest中我想在这种方法中等待直到我成功连接到ftp服务器然后才开始重新编写目录和文件。 如果连接服务器时出现erorr /问题,请将其显示给具有标签的用户,并停止后台工作。

但是如果他在操作开始之前成功连接到ftp服务器,那么整个想法就是给用户一些信息。

1 个答案:

答案 0 :(得分:1)

当您在GetWebReqeust中遇到错误时,您已经返回NULL值意味着您无法获得有效的连接。在GetDirectoryListning中,您应该捕获此NULL值并将其抛出到您的后台DoWork事件。在那里你可以检查null,如果需要,在后台worker上调用.cancel方法。这将完成dowork事件并触发RunWorkerComplete事件。

然后使用RunWorkerCompletedEventHandler将标签设置为您希望在连接失败时显示的值。 Microsoft写了一个如何执行此操作的示例here