简体   繁体   English

将文件上传到FTP服务器

[英]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. 我的应用程序的目的是,它必须将文件上传到FTP服务器,然后将本地文件移动到“存档”文件夹。 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. 是我的Filestream或Stream锁定了我的文件。 When i surround Filestream and Stream by using it doesn't uploade the files to the FTP as it does wihtout using . 当我被包围文件流和数据流using它的文件,因为它wihtout不uploade到FTP 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. 只需 foreach循环结束之前添加fileStream.Close()即可。

Try using FileStream.Dispose after you're done. 完成后,尝试使用FileStream.Dispose This should have the same effect as 'using'. 这应与“使用”具有相同的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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