Friday 15 July 2011

c# - how can avoid the InvalidOperationException in the following method? -


So, I have a method that "scans" an FTP server first it scans the root, and It determines which content is the file and which folder it is, and add them to two separate collections (string lists for folders and strings, int typed dictionaries for files). And finally it calls itself a method ... and runs in the statement that checks the count of the list if it is zero, then the method scans the root folder. Otherwise it should insert the first element of the list at the FTP address and check that folder. And here's the problem every time I try to execute the method, the second time (after the scanning of the root has ended) an invalid operation throws an exception because "the collection was modified, the calculation can not be executed" I How can I escape?

Here's the code:

  Internal Zero ListFilesOnServer () {ArrayList files = new ArrayList (); If (directories.Count == 0) {try {FtpWebRequest ftpwrq = (FtpWebRequest) WebRequest.Create (server); Ftpwrq.Credentials = New network credentials (user, passw); Ftpwrq.method = WebRequestMethods.Ftp.List directory; Ftpwrq.KeepAlive = false; FtpWebResponse fresponse = (FtpWebResponse) ftpwrq.GetResponse (); Streamer sr = new streamer (fresponse.GetResponsestream ()); String temp = ""; While ((temp = sr.ReadLine ())! = Null {files.Add (temp); } Temp = String.Empty; Sr.Close (); Fresponse.Close (); DirOrFile (files); } Hold (exception e) {message box. Show (E. Message); }} Else {foreach (string file in directory) {try {FtpWebRequest ftpwrq = (FtpWebRequest) WebRequest.Create (server + "/" + file); Ftpwrq.Credentials = New network credentials (user, passw); Ftpwrq.method = WebRequestMethods.Ftp.List directory; Ftpwrq.KeepAlive = false; FtpWebResponse fresponse = (FtpWebResponse) ftpwrq.GetResponse (); Streamer sr = new streamer (fresponse.GetResponsestream ()); String temp = ""; While ((temp = sr.ReadLine ())! = Null {files.Add (temp); } Temp = String.Empty; Sr.Close (); Fresponse.Close (); DirOrFile (files); } Hold (exception e) {message box. Show (E. Message); }}} Level = 1; ListFilesOnServer (); } In C #, the built-in archive has been structurally followed by a calculator Can not continue revised. There are two common ways around this:  

(1) Make a copy of the archive (for example with ToArray ()) and copy the copy:

  foreach (.ORARA) file in the string directory {...}   

(2) Use a conventional for-loop, it will only be right if you only add at the end of the list :

 for  (var i = 0; i & lt; directory.count; ++ i) {... code which can add directories}  < / Pre>  

No comments:

Post a Comment