webclient只能实现简单的上传与下载,不能判断服务器上文件是否存在等操作,当文件不存在时下载会报异常;
示例代码:
static void Main(string[] args)
{
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential("sww", "123");
int j = 6;
string ftp = "ftp://192.168.0.20/";
for (int i = 1; i < j; i++)
{
string filename = i.ToString("00") + "_" + DateTime.Now.ToString("yyyyMMdd") + ".xls";
string path = ftp + filename;
string localaddress = @"C:\Users\sww\Desktop\xls\" + filename;
try
{
wc.DownloadFile(path, localaddress);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
Console.WriteLine("Error,the file is not exist!");
}
}
Console.WriteLine("OK");
}
而ftpclient是一个别人封装好的类,封装了原始的ftpWebRequest和ftpWebResopnse等上传下载的一些复杂操作,使用这个类可以像操作webclient一样简单的使用
示例:控制台应用程序实现下载:
static void Main(string[] args)
{
FtpClient fc = new FtpClient("192.168.0.20", "sww", "123");
for (int i = 1; i < 6; i++)
{
string address = "ftp://192.168.0.20/";
string filename = i.ToString("00")+ "_" + DateTime.Now.ToString("yyyyMMdd")+ ".xls";
string path = address + filename;
string localaddress = @"C:\Users\sww\Desktop\xls\" + filename;
if (fc.CheckFileExist(filename))
{
fc.Download(filename, localaddress);
Console.WriteLine("文件已下载");
}
else {
Console.WriteLine("文件不存在");
}
}
}
winform窗体程序实现上传:
代码示例:
public partial class Form1 : Form
{
string ftp;
string pwd;
string uid;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog f = new OpenFileDialog();
if (f.ShowDialog() == DialogResult.OK)
{
// FtpClient fc = new FtpClient("192.168.0.20", "sww", "123");
FtpClient fc = new FtpClient(ftp, uid, pwd);
string path = f.FileName;
string filename = Path.GetFileName(path);
FileInfo fi = new FileInfo(path);
bool isright = fc.Upload(fi, filename);
if(isright)
{
MessageBox.Show("上传成功!");
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
ftp = ConfigurationManager.AppSettings["ftp"];
uid = ConfigurationManager.AppSettings["uid"];
pwd = ConfigurationManager.AppSettings["pwd"];
}
}