網路上有說,使用 WebClient 的作法碰到取很大檔案時 會有 timeout 問題,
目前自己測試 16MB 單檔是沒有問題。
using System.Net;
using System.IO;
----------------------------------
WebClient RMS = new WebClient();
RMS.Credentials = new NetworkCredential("ubuntu", "zzzzzz");
string FILE_NAME = "新增文字文件.txt";
byte[] fildData = RMS.DownloadData("ftp://10.1.1.195/tools/"+FILE_NAME);
FileStream file = File.Create(@"C:\Users\kuoming\Desktop\" + FILE_NAME);
file.Write(fildData, 0, fildData.Length);
file.Close();
listBox1.Items.Add(FILE_NAME);
完整程式碼:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
namespace _20100203_FTP_Client_test
{
public partial class Form1 : Form
{
string FILE_NAME = "";
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
this.Text= "目前目錄 為 10.1.1.195 / TOOLS ";
button1.Text = "Download";
listBox1.Items.AddRange(GetFileList());
listBox1.Sorted = true;
}
private void GET_FILE()
{
try
{
WebClient RMS = new WebClient();
RMS.Credentials = new NetworkCredential("ubuntu", "zzzzzz");
byte[] fildData = RMS.DownloadData("ftp://10.1.1.195/tools/" + FILE_NAME);
FileStream file = File.Create(@"C:\Users\kuoming\Desktop\" + FILE_NAME);
file.Write(fildData, 0, fildData.Length);
file.Close();
MessageBox.Show("OK");
}
catch (Exception QQ)
{
MessageBox.Show("目前不支援目錄下載...");
}
}
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + "10.1.1.195" + "/tools/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("ubuntu", "zzzzzz");
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
private void button1_Click(object sender, EventArgs e)
{
FILE_NAME = listBox1.SelectedItem.ToString();
GET_FILE();
}
}
}