views:

11

answers:

1

I think I have some memory issue with a function that should download a file from ftp server. The reason that I think it's a memory thing is because it works fine during debug (maybe it gives the garbage collector more time). Yet I thought that the using should solve this...

Just to be clear the function works when called once yet calling it several times in a for loop invokes the err message: 550 The specified network name is no longer available.

Please help Asaf

private void downloadFile(string sourceFile, string targetFolder)
            {            
                string remoteFile = sourceFile.Replace("\\","//");
                string localFolder = targetFolder + "\\" + sourceFile.Substring(sourceFile.LastIndexOf("\\")+1); 
                string filename = "ftp://" + ftpServerIP + "//" + remoteFile;

                FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(filename);
                ftpReq.Method = WebRequestMethods.Ftp.DownloadFile;
                ftpReq.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                ftpReq.UseBinary = true;
                ftpReq.Proxy = null;
                ftpReq.KeepAlive = false; //'3. Settings and action
                try
                {                
                    using (System.Net.FtpWebResponse response = (System.Net.FtpWebResponse)(ftpReq.GetResponse()))
                    {
                        using (System.IO.Stream responseStream = response.GetResponseStream())
                        {      
                            using (System.IO.FileStream fs = new System.IO.FileStream(localFolder, System.IO.FileMode.Create))
                            {
                                Byte[] buffer = new byte[2047];
                                int read = 0;
                                do
                                {
                                    read = responseStream.Read(buffer, 0, buffer.Length);
                                    fs.Write(buffer, 0, read);
                                } while (read == 0);
                                responseStream.Close();
                                fs.Flush();
                                fs.Close();
                            }
                            responseStream.Close();
                        }
                        response.Close();
                    }                
                }
                catch (WebException ex)
                { 
                    FtpWebResponse response = (FtpWebResponse)ex.Response;
                    Console.Out.WriteLine(response.StatusDescription);
                }
            }