如何避免以下方法中的InvalidOperationException?

时间:2013-06-22 17:12:06

标签: c# file ftp

所以,我有一个“扫描”ftp服务器的方法。首先它扫描根,并确定哪个内容是文件,哪个是文件夹,并添加两个不同的集合(文件夹和字符串的字符串列表,文件的int类型字典)。毕竟它会自称。该方法在if ... else语句中运行,该语句检查列表的计数。如果为零,则该方法扫描根文件夹。否则它应该将列表的第一个元素连接到ftp地址并检查该文件夹。这就是问题所在。每次我尝试执行该方法时,在第二次运行时(在root的扫描结束后),它会抛出InvalidOperation异常,因为“集合已被修改;枚举操作可能无法执行”。我怎么能避免这个?

顺便说一句,这是代码:

internal void ListFilesOnServer()
    {
        ArrayList files = new ArrayList();
        if (directories.Count == 0)
        {
            try
            {
                FtpWebRequest ftpwrq = (FtpWebRequest)WebRequest.Create(server);
                ftpwrq.Credentials = new NetworkCredential(user, passw);
                ftpwrq.Method = WebRequestMethods.Ftp.ListDirectory;
                ftpwrq.KeepAlive = false;
                FtpWebResponse fresponse = (FtpWebResponse)ftpwrq.GetResponse();
                StreamReader sr = new StreamReader(fresponse.GetResponseStream());
                string temp = "";
                while ((temp = sr.ReadLine()) != null)
                {
                    files.Add(temp);
                }
                temp = String.Empty;
                sr.Close();
                fresponse.Close();
                DirOrFile(files);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        else
        {
            foreach (string file in directories)
            {
                try
                {
                    FtpWebRequest ftpwrq = (FtpWebRequest)WebRequest.Create(server+"/"+file);
                    ftpwrq.Credentials = new NetworkCredential(user, passw);
                    ftpwrq.Method = WebRequestMethods.Ftp.ListDirectory;
                    ftpwrq.KeepAlive = false;
                    FtpWebResponse fresponse = (FtpWebResponse)ftpwrq.GetResponse();
                    StreamReader sr = new StreamReader(fresponse.GetResponseStream());
                    string temp = "";
                    while ((temp = sr.ReadLine()) != null)
                    {
                        files.Add(temp);
                    }
                    temp = String.Empty;
                    sr.Close();
                    fresponse.Close();
                    DirOrFile(files);
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message);
                }
            }
        }
        level = 1;
        ListFilesOnServer();
    }

1 个答案:

答案 0 :(得分:2)

在C#中,在对基础集合进行结构修改后,枚举器无法继续。有两种常见的方法:

(1)创建集合的副本(例如使用ToArray())并枚举副本:

foreach (string file in directories.ToArray()) {
    ...
}

(2)使用传统的for循环。只有在您只附加到列表末尾时,这才是正确的:

for (var i = 0; i < directories.Count; ++i) {
    ... code which might append to directories
}