如何重命名上传后的文件(How to rename a file after upload)

2019-07-01 22:15发布

我使用的服务器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”不能使用的方法等。

Answer 1:

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


Answer 2:

为什么不直接用代替正确的文件名上传吗? 与你真正想要的文件名更改您的第一道防线。

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

但是从你的老文件打开读取流。



文章来源: How to rename a file after upload