Unable to rename file with ftp methods when current user directory is different from root

半城伤御伤魂 提交于 2019-11-29 04:08:26

I have encountered a similar issue. The problem is that FtpWebRequest (incorrectly) prepends '/' to rename requests, as can be seen from this log (upload & rename):

URL: 
  http://127.0.0.1/Test.txt
FTP log:
  STOR Test.txt.part
  RNFR /Test.txt.part
  RNTO /Test.txt

Please note that this problem occurs only when you are uploading to the root directory. If you changed the URL to http://127.0.0.1/path/Test.txt, then everything would work fine.

My solution to this problem is to use %2E (dot) as the path:

URL:
  http://127.0.0.1/%2E/Test.txt
FTP log:
 STOR ./Test.txt.part
 RNFR ./Test.txt.part
 RNTO ./Test.txt

You have to url-encode the dot, otherwise FtpWebRequest would simplify the path "/./" to "/".

user756672

C#

using System.Net;
using System.IO;

Rename Filename on FTP Server function

C#

 private void RenameFileName(string currentFilename, string newFilename)
   {
       FTPSettings.IP = "DOMAIN NAME";
       FTPSettings.UserID = "USER ID";
       FTPSettings.Password = "PASSWORD";
       FtpWebRequest reqFTP = null;
       Stream ftpStream = null ;
       try
       {

           reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + FTPSettings.IP + "/" + currentFilename));
           reqFTP.Method = WebRequestMethods.Ftp.Rename;
           reqFTP.RenameTo = newFilename;
           reqFTP.UseBinary = true;
           reqFTP.Credentials = new NetworkCredential(FTPSettings.UserID, FTPSettings.Password);
           FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
           ftpStream = response.GetResponseStream();
           ftpStream.Close();
           response.Close();
       }
       catch (Exception ex)
       {
           if (ftpStream != null)
           {
               ftpStream.Close();
               ftpStream.Dispose();
           }
           throw new Exception(ex.Message.ToString());
       }
   }

   public static class FTPSettings
   {
       public static string IP { get; set; }
       public static string UserID { get; set; }
       public static string Password { get; set; }
   }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!