如何在上传后重命名文件

我必须在服务器上使用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’不能像方法一样使用。

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

为什么不直接用正确的文件名上传呢? 使用您真正想要的文件名更改第一行。

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

但是请从旧文件名中打开阅读流。