2012-10-23 39 views
2

我必須在服務器上使用Ftp協議上傳文件,並在上傳後重命名上傳的文件。如何在上傳後重命名文件

我可以上傳它,但不知道如何重命名它。

代碼如下所示:

FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName)); 
requestFTP.Proxy = null; 

requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword); 
requestFTP.Method = WebRequestMethods.Ftp.UploadFile; 
FileStream fStream = fileInfo.OpenRead(); 
int bufferLength = 2048; 
byte[] buffer = new byte[bufferLength]; 
Stream uploadStream = requestFTP.GetRequestStream(); 
int contentLength = fStream.Read(buffer, 0, bufferLength); 
while (contentLength != 0) 
{ 
    uploadStream.Write(buffer, 0, contentLength); 
    contentLength = fStream.Read(buffer, 0, bufferLength); 
} 
uploadStream.Close(); 
fStream.Close(); 

requestFTP = null; 

string newFilename = fileName.Replace(".ftp", ""); 
requestFTP.Method = WebRequestMethods.Ftp.Rename; // this like makes a problem 
requestFTP.RenameTo(newFilename); 

錯誤,我得到的是

錯誤2非可調用成員「System.Net.FtpWebRequest.RenameTo」 不能使用等的方法。

+0

'Method'和'Rename'都是'string's。他們不是功能。 – Default

+0

C#不提供直接重命名方法。您應該在服務器中用新名稱複製文件並刪除舊文件。 – 2012-10-23 08:23:31

回答

11

RenameTo是一個屬性,而不是一個方法。您的代碼應爲:

// requestFTP has been set to null in the previous line 
requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + fileName)); 
requestFTP.Proxy = null; 
requestFTP.Credentials = new NetworkCredential(ftpUser, ftpPassword); 

string newFilename = fileName.Replace(".ftp", ""); 
requestFTP.Method = WebRequestMethods.Ftp.Rename; 
requestFTP.RenameTo = newFilename; 
requestFTP.GetResponse(); 
-1

爲什麼不直接用正確的文件名上傳呢?用你真正想要的文件名改變你的第一行。

FtpWebRequest requestFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServer + "/" + "httpdocs/webroot/" + destination + "/" + newFileName)); 

但是請打開您的舊文件名的閱讀流。

+2

通常,此方法用於表示輪詢應用程序文件已完成上傳。 FTP的樂趣。 – Sam

+0

Tnx,但我真的需要用一些tmp名稱複製文件,然後將其重命名爲它的本機名稱。 – user198003

+1

爲什麼不直接回答OP? – Christian