Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - How to rename a file after upload

I have to upload file using Ftp protocol on server, and rename uploaded file after uploading.

I can upload it, but don't know how to rename it.

Code looks like this:

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

Error I'm getting is

Error 2 Non-invocable member 'System.Net.FtpWebRequest.RenameTo' cannot be used like a method.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

RenameTo is a property, not a method. Your code should read:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...