-1

我无法将我的 Stream 转换为 MemoryStream。我想这样做,因为我想删除我上传到 FTP 服务器的文件。当我尝试删除文件或将文件移动到另一个文件夹时,我收到一个异常,告诉我该文件正在被另一个进程使用。此应用程序的目的是将文件上传到 FTP 服务器,并将文件移动到存档文件夹。这是我的代码:

public void UploadLocalFiles(string folderName)
        {
            try
            {

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

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

                    FileInfo fileInfo = new FileInfo(localPath + @"\" + fileName);
                    FileStream fileStream = fileInfo.OpenRead();

                    int bufferLength = 2048;
                    byte[] buffer = new byte[bufferLength];

                    Stream uploadStream = reqFTP.GetRequestStream();

                    int contentLength = fileStream.Read(buffer, 0, bufferLength);
                    var memoStream = new MemoryStream();
                    uploadStream.CopyTo(memoStream);
                    memoStream.ToArray();
                    uploadStream.Close();

                    while (contentLength != 0)
                    {
                        memoStream.Write(buffer, 0, bufferLength);
                        contentLength = fileStream.Read(buffer, 0, bufferLength);

                    }
                }

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

        }

当我到达这行代码时:

 uploadStream.CopyTo(memoStream);

我收到一个异常,告诉我这个 Stream 无法读取。

我该如何解决这个问题?

4

1 回答 1

1

uploadStream.CopyTo(memoStream);失败,因为您试图复制只写 FTP 请求流。我不确定您的代码在做什么(在一个地方进行许多复制/读取操作的方式),所以我不能推荐修复它的方法。

FileStream也正在锁定文件。您的代码至少缺少using构造或Close调用对象。DisposefileStream

旁注:使用/为每个流手动using编写要容易得多(请注意,您的代码不会在出现异常时关闭流,因为您不会调用 close inside )。tryfinallyfinally

于 2012-09-25T08:05:34.373 回答