FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
refer: http://sureshjangid.blogspot.com/2010/03/ftp-file-rename-in-c-win-application.html
FTP File Rename In C# Win Application
// Posted By Suresh
Create a FtpWebRequest with the source file name, set the Method-Property of the FtpWebRequest to Use System.Net.WebRequestMethods.Ftp.Rename and set the RenameTo-Property of the FtpWebRequest to the new file name.
FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create("oldName");
request.Method = System.Net.WebRequestMethods.Ftp.Rename;
request.RenameTo = "newName";
自已按上面的方法写了个例子如下:
public void Test_Ftp_rename()
{
try
{
string oldName = "AWG5_FeedConvertCreateItem_20111108_004702_885_.xml";
string filePath = "10.1.24.143"
+ "/" + "MKTPLS_Batch/Inbound/CreateItem" + "/";
//FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create("ftp://" + filePath + oldName);
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + filePath + "/" + oldName));
//ftp.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["BatchFtpUserID"], ConfigurationManager.AppSettings["BatchFtpPassword"]);
ftp.Method = System.Net.WebRequestMethods.Ftp.Rename;
//ftp.RenameTo = "./" + "MKTPLS_Batch/Inbound/CreateItem" + "/" + "OTH_TEST_.xml";
ftp.RenameTo = "OTH_TEST_1.xml";
ftp.UseBinary = true;
ftp.Credentials = new NetworkCredential("anonymous", "abc");
FtpWebResponse response = (FtpWebResponse)ftp.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
Assert.IsEmpty(ex.Message);
}
}
注意:由于在用FtpWebRequest.Create方法时,已经传入了路径,所以FTP连接后的当前路径就是在Create中指定的路径,如果你只是rename文件。则renameTo的文件名,不需要再指明路径了,如果你会把文件移到其它地方,写相对路径时请记住当前路径就是Create中指定的路径。或是直接写绝对路径(根目录为"\")。不然程序会报找不到文件的错误!