c# - FTP文件下载C#
问题描述
在我的代码中,我想从 FTP 服务器下载一个特定的文件到我的本地机器。我得到一个如下所示的异常
System.InvalidCastException: Unable to cast object of type: 'System.Net.HttpWebRequest' to type 'System.Net.FtpWebRequest' at FTPapp.ftpdownload.Download(String remoteFile, String localFile)
我的代码:
namespace FTPapp
{
public partial class ftpdownload : Form
{
private string Host = null;
private string user = null;
private string pass = null;
private string SSH = null;
private FtpWebRequest ftprequest = null;
private FtpWebResponse ftpresponse = null;
private Stream ftpStream = null;
private int buffersize = 2048;
public ftpdownload()
{
InitializeComponent();
}
public ftpdownload(string hostIP, string username, string password ,string SSHkey)
{
Host = hostIP;
user = username;
pass = password;
SSH = SSHkey;
}
public void Download(string remoteFile, string localFile)
{
try
{
ftprequest = (FtpWebRequest)FtpWebRequest.Create(Host + "/" + remoteFile);
ftprequest.Credentials = new NetworkCredential(user, pass ,SSH);
ftprequest.UseBinary = true;
ftprequest.UsePassive = true;
ftprequest.KeepAlive = true;
ftprequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpresponse = (FtpWebResponse)ftprequest.GetResponse();
ftpStream = ftpresponse.GetResponseStream();
FileStream localFileStream = new FileStream(localFile, FileMode.Create);
byte[] byteBuffer = new byte[buffersize];
`enter code here` int bytesRead = ftpStream.Read(byteBuffer, 0, buffersize);
try
{
while (bytesRead > 0)
{
localFileStream.Write(byteBuffer, 0, bytesRead);
bytesRead = ftpStream.Read(byteBuffer, 0, buffersize);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
localFileStream.Close();
ftpStream.Close();
ftpresponse.Close();
ftprequest= null;
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void BackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
txtServer.Text = "http://ftpsite.com";
txtUsername.Text = "";
txtPassword.Text = @"";
txtFilename.Text = @"";
txtSSHKey.Text = "";
}
private void BtnDownload_Click(object sender, EventArgs e)
{
ftpdownload ftp = new ftpdownload("http://ftpsite.com" ,"","","");
ftp.Download(@"Remotepath", @"local path");
}
}
}
解决方案
如果不检查,我们无法确定该链接是 FTP Uri。
如microsoft 文档中所述,您需要ftp://
在主机名之前使用,例如:ftp://contoso.com/someFile.txt
.
那么,如何解决您的问题呢?
首先,您应该添加ftp://
到您的链接。之后,您可以创建一个Uri
对象并检查它的方案是否为Uri.UriSchemeFtp
. 如果没有,请返回。
推荐阅读
- postgresql - PostgreSQL:使用字符串和变量创建外部表
- node.js - 有没有一种简单的方法可以使用 Node/PostgreSQL 对任何类型的文件进行简单的文件上传?
- python - Django 页面限制(管理员和成员可以看到)
- javascript - FullCalendar 不会更改语言
- node.js - 无法通过winapi获取窗口截图
- javascript - javascript eval() 函数的参数
- c++ - 是 std::transform SIMD 功能吗?
- java - 如何使用双向 OneToMany 关系避免无限递归,并从双方获取信息?
- c++ - C++ set:根据自定义比较器查找和删除元素
- java - 根据游戏的输赢增加和减少“金额”