Lahib
Lahib

Reputation: 1365

Uploading files to an FTP server

The purpose of my application is, it has to uploade files to a FTP server, and then move the local files to an Archive folder. Here is my code:

public void UploadLocalFiles(string folderName)
        {
            try
            {

                string localPath = @"\\Mobileconnect\filedrop_to_ssis\" + folderName;
                string[] files = Directory.GetFiles(localPath);

                foreach (string filepath in files)
                {
                    string fileName = Path.GetFileName(filepath);
                    localFileNames = files;
                    reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp:...../inbox/" + fileName));
                    reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                    reqFTP.UsePassive = true;
                    reqFTP.UseBinary = true;
                    reqFTP.ServicePoint.ConnectionLimit = files.Length;
                    reqFTP.Credentials = new NetworkCredential("username", "password");
                    reqFTP.EnableSsl = true;
                    ServicePointManager.ServerCertificateValidationCallback = Certificate;

                    FileInfo fileInfo = new FileInfo(localPath + @"\" + fileName);
                    byte[] fileContents = new byte[fileInfo.Length];

                    FileStream fileStream = fileInfo.OpenRead();

                    fileStream.Read(fileContents, 0, Convert.ToInt32(fileInfo.Length));


                    Stream writer = reqFTP.GetRequestStream();

                    writer.Write(fileContents, 0, fileContents.Length);
                }

                reqFTP.Abort();
            }
            catch (Exception e)
            {
                Console.WriteLine("Error in GetLocalFileList method!!!!!" + e.Message);
            }

        }

After runing this method, i cant move the files, i get this exception message : "Cant access file, the file is being used by another process". It is my Filestream or Stream that is locking my files. When i surround Filestream and Stream by using it doesn't uploade the files to the FTP as it does wihtout using. I cant see why, can anyone help with this ?

Upvotes: 0

Views: 2223

Answers (2)

Jakub Szułakiewicz
Jakub Szułakiewicz

Reputation: 840

The problem is in filestream, that you are using to read files.

You need to close it.

Just add fileStream.Close() just before end of foreach loop.

Upvotes: 2

Amr
Amr

Reputation: 1995

Try using FileStream.Dispose after you're done. This should have the same effect as 'using'.

Upvotes: 1

Related Questions