首页 / C# / C# FTP上传和下载
C# FTP上传和下载
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了C# FTP上传和下载,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2449字,纯文字阅读大概需要4分钟。
内容图文
![C# FTP上传和下载](/upload/InfoBanner/zyjiaocheng/612/5c41209adc114d73b6ab8eee9226afe1.jpg)
需要引入命名空间 using System.Net;
上传文件:
/// <summary> /// 上传文件到ftp /// </summary> /// <param name="UploadPath">上传的路径</param> /// <param name="FilePath">本地文件路径</param> /// <param name="User">ftp用户名</param> /// <param name="Password">ftp密码</param> /// public void UploadFtp(string UploadPath, string FilePath, string User, string Password) { WebClient request = new WebClient(); request.UploadDataCompleted += new UploadDataCompletedEventHandler(request_UploadDataCompleted); request.Credentials = new NetworkCredential(User, Password); System.IO.FileStream myStream = new System.IO.FileStream(FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] dataByte = new byte[myStream.Length]; myStream.Read(dataByte, 0, dataByte.Length); myStream.Close(); Uri u = new Uri(UploadPath + "/" + System.IO.Path.GetFileName(FilePath)); request.UploadDataAsync(u, "STOR", dataByte, dataByte); void request_UploadDataCompleted(object AS, UploadDataCompletedEventArgs asd) { byte[] BUF = (byte[])asd.UserState; if (asd.Error == null) MessageBox.Show("上传完成,文件大小:" + BUF.Length + "b", "上传完成",MessageBoxButtons.OK,MessageBoxIcon.Information); else MessageBox.Show(asd.Error.Message, "上传出现错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
下载文件:
/// <summary> /// 从ftp下载文件 /// </summary> /// <param name="FtpUri">ftp地址</param> /// <param name="FileName">需要下载的文件名</param> /// <param name="SavePath">保存到本地的路径</param> /// <param name="User">ftp用户名</param> /// <param name="Password">ftp密码</param> public void DownloadFTP(string FtpUri,string FileName,string SavePath,string User,string Password) { FtpWebRequest reqFTP; System.IO.FileStream outputStream = new System.IO.FileStream(SavePath + "\\" + FileName, FileMode.Create); reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpUri + FileName)); reqFTP.Method = WebRequestMethods.Ftp.DownloadFile; reqFTP.UseBinary = true; reqFTP.Credentials = new NetworkCredential(User, Password); reqFTP.UsePassive = false; FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse(); Stream ftpStream = response.GetResponseStream(); long cl = response.ContentLength; int bufferSize = 2048; int readCount; byte[] buffer = new byte[bufferSize]; readCount = ftpStream.Read(buffer, 0, bufferSize); while (readCount > 0) { outputStream.Write(buffer, 0, readCount); readCount = ftpStream.Read(buffer, 0, bufferSize); } ftpStream.Close(); outputStream.Close(); response.Close(); }
内容总结
以上是互联网集市为您收集整理的C# FTP上传和下载全部内容,希望文章能够帮你解决C# FTP上传和下载所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。