gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:47:52 27 4
gpt4 key购买 nike

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

ftp://1.1.1.1/MAIN/Dir1

我需要将文件移动到:

ftp://1.1.1.1/MAIN/Dir2

我发现有几篇文章推荐使用重命名命令,因此我尝试了以下操作:

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

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

The remote server returned an error: (550) File unavailable (e.g., file not found, no access).

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

是否应该可以像这样在目录之间移动文件,如果不能,怎么可能?

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

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

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

ftp://1.1.1.1/%2fMAIN/Dir1/MyFile.txt

对于源路径和目标路径 - 但这也没有区别。

我找到了 this文章,似乎说将目标指定为相对路径会有所帮助 - 似乎无法将绝对路径指定为目标。

reqFTP.RenameTo = “../Dir2/MyFile.txt";

最佳答案

遇到了同样的问题,找到了另一种解决问题的方法:

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;

}

关于c# - 如何使用 FTP 在目录之间移动文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864925/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com