winform如何下载FTP上的文件?
winform如何下载FTP上的文件?下面是我在网上找的代码,运行后提示以下错误:
"远端伺服器传回一個錯誤: (530) 未登入"。是不是还需要登陆什么的?这代码要如何修改?
private void button1_Click(object sender, EventArgs e)
{
DownLoad(@"ftp://ni.hao.com/123.rar", "F:\");//想问下这里的两个参数可以这样写吗?
}
private void DownLoad(string URL,string Dir)
{
WebClient client = new WebClient();
string fileName = URL.Substring(URL.LastIndexOf("/") + 1); //被下载的文件名
string Path = Dir + fileName; //另存为的绝对路径+文件名
try
{
WebRequest myre = WebRequest.Create(URL);
}
catch(Exception exp)
{
MessageBox.Show(exp.Message, "Error");
}
try
{
client.DownloadFile(URL, fileName);
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
byte[] mbyte = r.ReadBytes((int)fs.Length);
FileStream fstr = new FileStream(Path, FileMode.OpenOrCreate, FileAccess.Write);
fstr.Write(mbyte, 0, (int)fs.Length);
fstr.Close();
}
catch (Exception exp)
{
MessageBox.Show(exp.Message, "Error");
}
}
[最优解释]
官方的:http://msdn.microsoft.com/zh-cn/library/system.net.ftpwebrequest.aspx
非官方的:
private void DownloadFileFTP()
{
string inputfilepath = @"C:\Temp\FileName.exe";
string ftphost = "xxx.xx.x.xxx";
string ftpfilepath = "/Updater/Dir1/FileName.exe";
string ftpfullpath = "ftp://" + ftphost + ftpfilepath;
WebClient request = new WebClient();
request.Credentials = new NetworkCredential("UserName", "P@55w0rd");
byte[] fileData = request.DownloadData(ftpfullpath);
FileStream file = File.Create(inputfilepath);
file.Write(fileData, 0, fileData.Length);
file.Close();
MessageBox.Show("Download Complete");
}