【问题标题】:Uploading files to an FTP server将文件上传到 FTP 服务器
【发布时间】:2012-09-26 07:00:01
【问题描述】:

我的应用程序的目的是,它必须将文件上传到 FTP 服务器,然后将本地文件移动到存档文件夹。这是我的代码:

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);
            }

        }

运行此方法后,我无法移动文件,我收到此异常消息:“无法访问文件,该文件正在被另一个进程使用”。是我的 Filestream 或 Stream 锁定了我的文件。当我用using 包围Filestream 和Stream 时,它不会像没有using 那样将文件上传到FTP。我不明白为什么,有人可以帮忙吗?

【问题讨论】:

    标签: c# c#-4.0 ftp c#-3.0 ftpwebrequest


    【解决方案1】:

    问题出在你用来读取文件的文件流中。

    你需要关闭它。

    只需在 foreach 循环的结束之前添加fileStream.Close()

    【讨论】:

    • 感谢您的提示。它终于奏效了。我以为是我的 Stream 锁定了文件。但当然是 Filestream,因为它可以访问本地文件。
    【解决方案2】:

    完成后尝试使用FileStream.Dispose。这应该与“使用”具有相同的效果。

    【讨论】:

    • 我试过了,但又试了一次,但没有帮助。我得到同样的例外。 IOException: 该进程无法访问该文件,因为它正被另一个进程使用
    • 我认为你不应该使用 FtpWebRequest.Abort,而应该使用 Close,就像这里 blog.logiclabz.com/c/…
    • 在那个例子中,他没有关闭 FtpWebRequest 破坏 FileStreamStream
    • 你是对的,对此感到抱歉。我的观点是:上述示例应该可以工作。尝试修改代码以匹配它。
    • 我多次尝试修改此代码。流上传文件,但只要我使用Writer.Close()using,文件就会从 FTP 服务器中删除。但我不能只使用Writer.Flush() insted 吗??