2012-09-25 68 views
-1

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

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

我得到一个异常告诉我,这个流着读。

我该如何解决这个问题?

+0

在移动文件之前,您需要完成读取上传流的操作。 – Liam

+0

uploadstream正在锁定该文件,我不明白为什么以及在何处 – Lahib

回答

1

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

另外您的FileStream正在锁定文件。您的代码缺少using构造或CloseDispose至少调用fileStream对象。

边注:使用using是显著更容易,对于通过手中的每个流写try/finally(请注意,您的代码不会关闭流在例外的情况下,因为你不打电话来关闭内部finally)。

+0

当使用''using'应用程序包围我的文件流不会将文件上传到FTP服务器出于某种原因 – Lahib