简体   繁体   中英

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 ?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM