在C#中操作FTP完成rename操作

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

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://stackoverflow.com/questions/1307372/ftpwebrequest-move-file

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中指定的路径。或是直接写绝对路径(根目录为"\")。不然程序会报找不到文件的错误!


  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值