使用c#将FTP文件传输到主机,包括数据集-将FTP脚本转换为FtpWebRequest代码

本文关键字:FTP 脚本 转换 FtpWebRequest 代码 数据集 文件 传输 使用 主机 包括 | 更新日期: 2023-09-27 17:49:59

我使用cmd (Windows)将文件发送到IBM大型机并工作良好,它是这样的:

Open abc.wyx.state.aa.bb
User
Pass
lcd c:'Transfer>
Put examplefile 'ABCD.AA.C58FC.ABC1FD.ZP3ABC'
close
bye

我需要将其转换为c#。我一直在尝试使用FtpWebRequest,但没有运气。我猜我不知道如何包含数据集。当我运行应用程序时,我得到了以下错误:

((System.Exception)(特异))。消息"远程服务器返回一个错误:(550)文件不可用(例如,未找到文件,无法访问)。"550无法存储远程服务器返回一个错误:(550)文件不可用(例如,文件未找到,无法访问).

((FtpWebResponse) ex.Response)。状态描述"550无法存储/'ABCD.AA.C58FC.ABC1FD.ZP3ABC/examplefile''r'n"

这是我在c#中得到的

string user = "user";
string pwd = "password";
string ftpfullpath = @"ftp://abc.wyx.state.aa.bb//'ABCD.AA.C58FC.ABC1FD.ZP3ABC'/examplefile'";
try
{
     FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
     ftp.Credentials = new NetworkCredential(user, pwd);
     ftp.KeepAlive = true;
     ftp.UseBinary = false;  //Use ascii.              
     ftp.Method = WebRequestMethods.Ftp.UploadFile;
     FileStream fs = File.OpenRead(inputfilepath);
     byte[] buffer = new byte[fs.Length];
     fs.Read(buffer, 0, buffer.Length);
     fs.Close();
     Stream ftpstream = ftp.GetRequestStream();
     ftpstream.Write(buffer, 0, buffer.Length);
     ftpstream.Close();
}
catch (WebException ex)
{
     String status = ((FtpWebResponse)ex.Response).StatusDescription;
     throw new Exception(status);
}

使用c#将FTP文件传输到主机,包括数据集-将FTP脚本转换为FtpWebRequest代码

您没有指定在哪个平台上运行ftp脚本。我猜是Windows

当您使用Windows ftp命令put时,如:

put localpath remotepath

在FTP服务器上导致以下调用:

STOR remotefile

同样,如果您使用FtpWebRequest和URL,如

ftp://example.com/remotepath

在FTP服务器上导致以下(相同的)调用:

STORE remotepath

请注意,主机名(example.com)后的第一个斜杠被省略了。


这意味着您的ftp脚本命令:
Open abc.wyx.state.aa.bb
...
Put examplefile 'ABCD.AA.C5879.ABC123.123ABC'

翻译成FtpWebRequest URL:

string ftpfullpath = @"ftp://abc.wyx.state.aa.bb/'ABCD.AA.C5879.ABC123.123ABC'";

两者都会导致FTP服务器上的这个调用:

STOR 'ABCD.AA.C5879.ABC123.123ABC'

相反,你的ftp代码

string ftpfullpath = @"ftp://abc.wyx.state.aa.bb//'ABCD.AA.C5879.ABC123.123ABC'/examplefile'";

结果:

STOR /'ABCD.AA.C5879.ABC123.123ABC'/examplefile'

在主机上看起来不正确。


我的c#代码的会话记录:

USER user
331 Password required for user
PASS password
230 Logged on
OPTS utf8 on
200 UTF8 mode enabled
PWD
257 "/" is current directory.
TYPE A
200 Type set to A
PASV
227 Entering Passive Mode (zzz,zzz,zzz,zzz,193,162)
STOR 'ABCD.AA.C5879.ABC123.123ABC'
150 Connection accepted
226 Transfer OK

ftp脚本的会话记录:

USER user
331 Password required for user
PASS password
230 Logged on
PORT zzz,zzz,zzz,zzz,193,186
200 Port command successful
STOR 'ABCD.AA.C5879.ABC123.123ABC'
150 Opening data channel for file transfer.
226 Transfer OK
QUIT
221 Goodbye

我已经在FileZilla FTP服务器上测试了这个,所以很明显FTP服务器的响应在大型机FTP上是不同的。但是来自客户端的FTP命令应该是相同的