我有一个程序需要将文件从 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();
但这似乎不起作用——我收到以下错误:
远程服务器返回错误:(550) 文件不可用(例如,未找到文件、无法访问)。
起初我认为这可能与权限有关,但据我所知,我拥有整个 FTP 站点的权限(它位于我的本地 PC 上,并且 uri 解析为 localhost)。
是否可以像这样在目录之间移动文件,如果不能,怎么可能?
针对已提出的一些观点/建议:
- 我可以从源目录下载相同的文件,所以它肯定存在(我所做的是先下载文件,然后将其移动到其他地方)。
- 我可以从浏览器访问 ftp 站点(源目录和目标目录)
- ftp 服务器在我本地计算机上我自己的 IIS 实例下运行。
- 路径和大小写正确,没有特殊字符。
此外,我尝试将目录路径设置为:
ftp://1.1.1.1/%2fMAIN/Dir1/MyFile.txt
对于源路径和目标路径 - 但这也没有区别。
I found this http://naveedhanif.wordpress.com/2010/05/17/ftpwebrequest-renameto-directory/文章,似乎说将目的地指定为相对路径会有所帮助 - 似乎不可能指定绝对路径作为目的地。
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;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)