我無法將我的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);
我得到一個異常告訴我,這個流着讀。
我該如何解決這個問題?
在移動文件之前,您需要完成讀取上傳流的操作。 – Liam
uploadstream正在鎖定該文件,我不明白爲什麼以及在何處 – Lahib