博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
FTP 文件上传跟下载
阅读量:6819 次
发布时间:2019-06-26

本文共 8374 字,大约阅读时间需要 27 分钟。

https://jingyan.baidu.com/article/f54ae2fc3521d51e92b849c7.html

注意电脑用户名称不能是FTP之前设置为FTP用户名称一直导致登录错误 如上网址可以进行FTP的电脑设置

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Net;using System.IO;using System.Threading;namespace TCPFileDownUp{    class Program    {        static void Main(string[] args)        {            //暂时只做了文件上传 没有做文件夹上传即文件夹内容中所包含的所有东西上传操作            List
dirs = GetDirctory("LocalUserDemo"); DownloadFile(@"F:\下载的文件", "LocalUserDemo", "DUCT.zip", @"192.168.1.43:58888/", "fuck", "1234"); Console.ReadKey(); FileInfo fileInfo = new FileInfo(@"F:\黄成\PE1110.zip"); UploadFile(fileInfo, "LocalUserDemo", @"192.168.1.43:58888/", "fuck", "1234"); Console.ReadKey(); } ///
/// 上传文件 /// ///
需要上传的文件 ///
目标路径 ///
ftp地址 ///
ftp用户名 ///
ftp密码 public static void UploadFile(FileInfo fileinfo, string targetDir, string hostname, string username, string password) { //1. check target string target; if (targetDir.Trim() == "") { return; } target = Guid.NewGuid().ToString(); //使用临时文件名 string URI = "FTP://" + hostname + "/" + targetDir + "/" + target; ///WebClient webcl = new WebClient(); System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); //设置FTP命令 设置所要执行的FTP命令, //ftp.Method = System.Net.WebRequestMethods.Ftp.ListDirectoryDetails;//假设此处为显示指定路径下的文件列表 ftp.Method = System.Net.WebRequestMethods.Ftp.UploadFile; //指定文件传输的数据类型 ftp.UseBinary = true; ftp.UsePassive = true; //告诉ftp文件大小 ftp.ContentLength = fileinfo.Length; //缓冲大小设置为2KB const int BufferSize = 2048; byte[] content = new byte[BufferSize - 1 + 1]; int dataRead; int sumTotal = 0; //打开一个文件流 (System.IO.FileStream) 去读上传的文件 using (FileStream fs = fileinfo.OpenRead()) { try { //把上传的文件写入流 using (Stream rs = ftp.GetRequestStream()) { do { //每次读文件流的2KB dataRead = fs.Read(content, 0, BufferSize); //进度 sumTotal += dataRead; double RateOfProgress = sumTotal * 1.0 / fileinfo.Length; Console.WriteLine(RateOfProgress); rs.Write(content, 0, dataRead); } while (!(dataRead < BufferSize)); rs.Close(); } } catch (Exception ex) { } finally { fs.Close(); } } ftp = null; //设置FTP命令 ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.Rename; //改名 ftp.RenameTo = fileinfo.Name; try { ftp.GetResponse(); } catch (Exception ex) { //出问题就删除 ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; //删除 ftp.GetResponse(); throw ex; } finally { //fileinfo.Delete(); } // 可以记录一个日志 "上传" + fileinfo.FullName + "上传到" + "FTP://" + hostname + "/" + targetDir + "/" + fileinfo.Name + "成功." ); ftp = null; #region /***** *FtpWebResponse * ****/ //FtpWebResponse ftpWebResponse = (FtpWebResponse)ftp.GetResponse(); #endregion } ///
/// 从ftp服务器上获得文件夹列表 /// ///
服务器下的相对路径 ///
public static List
GetDirctory(string RequedstPath) { List
strs = new List
(); try { string uri = @"ftp://192.168.1.43:58888/" + RequedstPath; //目标路径 path为服务器地址 FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential("fuck", "1234"); reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails; WebResponse response = reqFTP.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream());//中文文件名 string line = reader.ReadLine(); while (line != null) { if (line.Contains("
")) { string msg = line.Substring(line.LastIndexOf("
") + 5).Trim(); strs.Add(msg); } line = reader.ReadLine(); } reader.Close(); response.Close(); return strs; } catch (Exception ex) { Console.WriteLine("获取目录出错:" + ex.Message); } return strs; } private static FtpWebRequest GetRequest(string URI, string username, string password) { //根据服务器信息FtpWebRequest创建类的对象 FtpWebRequest result = (FtpWebRequest)FtpWebRequest.Create(URI); //提供身份验证信息 result.Credentials = new System.Net.NetworkCredential(username, password); //设置请求完成之后是否保持到FTP服务器的控制连接,默认值为true result.KeepAlive = false; return result; } ///
/// 获取文件大小 /// ///
ip服务器下的相对路径 ///
文件大小
public static int GetFileSize(string file, string username, string password) { StringBuilder result = new StringBuilder(); FtpWebRequest request; try { request = (FtpWebRequest)FtpWebRequest.Create(new Uri(file)); request.UseBinary = true; request.UsePassive = false; request.KeepAlive = false; request.Credentials = new NetworkCredential(username, password);//设置用户名和密码 request.Method = WebRequestMethods.Ftp.GetFileSize; int dataLength = (int)request.GetResponse().ContentLength; return dataLength; } catch (Exception ex) { Console.WriteLine("获取文件大小出错:" + ex.Message); return -1; } } ///
/// 下载文件 /// ///
下载至本地路径 ///
ftp目标文件路径 ///
从ftp要下载的文件名 ///
ftp地址即IP ///
ftp用户名 ///
ftp密码 public static void DownloadFile(string localDir, string FtpDir, string FtpFile, string hostname, string username, string password) { string URI = "FTP://" + hostname + "/" + FtpDir + "/" + FtpFile; int FileTotal = GetFileSize(URI, username, password); string tmpname = Guid.NewGuid().ToString(); //本地路径 string localfile = localDir + @"\" + tmpname; System.Net.FtpWebRequest ftp = GetRequest(URI, username, password); ftp.Method = System.Net.WebRequestMethods.Ftp.DownloadFile; //很重要 如果要多次访问这个地方要为false keepAlive则设成false,一个查询请求完了后就关闭 因为上面做了一个查询 查询文件大小 ftp.KeepAlive = false; ftp.UseBinary = true; ftp.UsePassive = false; int bufferCount = 40960; //long f = ftp.ContentLength; FtpWebResponse response = (FtpWebResponse)ftp.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { using (FileStream fs = new FileStream(localfile, FileMode.CreateNew)) { try { byte[] buffer = new byte[bufferCount]; int read = 0; int TotalByte = 0; do { //把流写到buffer的byte数组中 read = responseStream.Read(buffer, 0, buffer.Length); //下载的进度 TotalByte += read; //下载的进度 double k = TotalByte * 1.0 / FileTotal; Console.WriteLine(k); //读 fs.Write(buffer, 0, read); } while (!(read == 0)); } catch (Exception ex) { //catch error and delete file only partially downloaded fs.Close(); //delete target file as it's incomplete File.Delete(localfile); throw ex; Console.WriteLine(ex.Message); } Console.WriteLine("over"); } } //using () //{ // using () // { // //loop to read & write to file // using () // { // } // } //} //try //{ // //File.Delete(localDir + @"\" + FtpFile); // //File.Move(localfile, localDir + @"\" + FtpFile); // //ftp = null; // //ftp = GetRequest(URI, username, password); // //ftp.Method = System.Net.WebRequestMethods.Ftp.DeleteFile; // //ftp.GetResponse(); //} //catch (Exception ex) //{ // File.Delete(localfile); // throw ex; //} // 记录日志 "从" + URI.ToString() + "下载到" + localDir + @"\" + FtpFile + "成功." ); //ftp = null; } }}

 

转载于:https://www.cnblogs.com/yangshasha/p/7879867.html

你可能感兴趣的文章
32位linux安装32位oracle11g-netca报错解决方法
查看>>
VBScript脚本实现在目录中自动获取某个文件
查看>>
依据奖品权重值实现的随机抽奖,PHP实现
查看>>
一些总结
查看>>
Unity3D入门中文版doc文档下载
查看>>
F5与BoCloud博云因技术结缘 携手加速容器生态系统在华落地
查看>>
Intent序列化
查看>>
js 计算两个时间的差
查看>>
有趣的Linux命令行功效
查看>>
解决PotPalyer不能拖放播放
查看>>
Linux安装mysql5.7
查看>>
HIVE常用操作以及函数
查看>>
【优达学城测评】SQL 支持许的数据类型(3)
查看>>
PHP CURL CURLOPT参数说明(curl_setopt)
查看>>
Learning NodeJs(1)
查看>>
怎么解决mysql远程连接报10038的错误
查看>>
js 父窗口可以找到子窗口的元素
查看>>
从FB10.3升级到11.0后几个问题的解决
查看>>
django使用MySql的基本步骤
查看>>
笔记《Java并发编程实战》[2]
查看>>