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' 不能像方法一样使用。

4

2 回答 2

12

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();
于 2012-10-23T08:25:39.993 回答
-1

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

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

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

于 2012-10-23T08:27:27.060 回答