如何使用FTP在目录之间移动文件?

Pau*_*els 19 c# ftp ftpwebrequest .net-3.5

我有一个程序需要在FTP服务器上将文件从一个目录移动到另一个目录.例如,文件位于:

ftp://1.1.1.1/MAIN/Dir1
Run Code Online (Sandbox Code Playgroud)

我需要将文件移动到:

ftp://1.1.1.1/MAIN/Dir2
Run Code Online (Sandbox Code Playgroud)

我发现有几篇文章建议使用Rename命令,所以我尝试了以下内容:

    Uri serverFile = new Uri(“ftp://1.1.1.1/MAIN/Dir1/MyFile.txt");
    FtpWebRequest reqFTP= (FtpWebRequest)FtpWebRequest.Create(serverFile);
    reqFTP.Method = WebRequestMethods.Ftp.Rename;
    reqFTP.UseBinary = true;
    reqFTP.Credentials = new NetworkCredential(ftpUser, ftpPass);
    reqFTP.RenameTo = “ftp://1.1.1.1/MAIN/Dir2/MyFile.txt";

    FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Run Code Online (Sandbox Code Playgroud)

但这似乎不起作用 - 我收到以下错误:

远程服务器返回错误:(550)文件不可用(例如,找不到文件,没有访问权限).

起初我认为这可能与权限有关,但据我所知,我拥有整个FTP站点的权限(它在我的本地PC上,并且uri被解析为localhost).

是否可以在这样的目录之间移动文件,如果没有,它怎么可能?

为了解决已提出的一些观点/建议:

  1. 我可以从源目录下载相同的文件,所以它肯定存在(我正在做的是首先下载文件,然后将其移动到其他地方).
  2. 我可以从浏览器(源目录和目标目录)访问ftp站点
  3. ftp服务器在我本地计算机上的自己的IIS实例下运行.
  4. 路径和大小写是正确的,没有特殊字符.

另外,我尝试将目录路径设置为:

ftp://1.1.1.1/%2fMAIN/Dir1/MyFile.txt
Run Code Online (Sandbox Code Playgroud)

源路径和目标路径都有 - 但这也没有区别.

我发现这篇文章,似乎说将目标指定为相对路径会有所帮助 - 似乎不可能将绝对路径指定为目标.

reqFTP.RenameTo = “../Dir2/MyFile.txt";
Run Code Online (Sandbox Code Playgroud)

小智 19

有同样的问题,并找到另一种方法来解决问题:

public string FtpRename( string source, string destination ) {
        if ( source == destination )
            return;

        Uri uriSource = new Uri( this.Hostname + "/" + source ), UriKind.Absolute );
        Uri uriDestination = new Uri( this.Hostname + "/" + destination ), UriKind.Absolute );

        // Do the files exist?
        if ( !FtpFileExists( uriSource.AbsolutePath ) ) {
            throw ( new FileNotFoundException( string.Format( "Source '{0}' not found!", uriSource.AbsolutePath ) ) );
        }

        if ( FtpFileExists( uriDestination.AbsolutePath ) ) {
            throw ( new ApplicationException( string.Format( "Target '{0}' already exists!", uriDestination.AbsolutePath ) ) );
        }

        Uri targetUriRelative = uriSource.MakeRelativeUri( uriDestination );


        //perform rename
        FtpWebRequest ftp = GetRequest( uriSource.AbsoluteUri );
        ftp.Method = WebRequestMethods.Ftp.Rename;
        ftp.RenameTo = Uri.UnescapeDataString( targetUriRelative.OriginalString );

        FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); 

        return response.StatusDescription; 

    }
Run Code Online (Sandbox Code Playgroud)


vla*_*lad 13

MSDN似乎建议您的路径被认为是相对的,因此它尝试使用提供的凭据登录到FTP服务器,然后将当前目录设置为该<UserLoginDirectory>/path目录.如果这与您的文件所在的目录不同,则会出现550错误.