123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330 |
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Text;
- using System.IO;
- namespace MOTINOVA_Motor_Factory_Set
- {
- public class ftp
- {
- #region
- string serverIP;
- string serverPort;
- string userId;
- string passWord;
- public bool IsNetConnected = false;
- public void FtpOption(string serverIP, string serverPort, string userId, string passWord)
- {
- this.serverIP = serverIP;
- this.serverPort = serverPort;
- this.userId = userId;
- this.passWord = passWord;
- }
- public bool CheckFtp()
- {
- try
- {
- Uri uri = new Uri(string.Format("ftp://{0}/{1}", serverIP, "/"));
- FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpRequest.Credentials = new NetworkCredential(userId, passWord);
- ftpRequest.Method = WebRequestMethods.Ftp.PrintWorkingDirectory;
- ftpRequest.Timeout = 2000;
- FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
- ftpResponse.Close();
- IsNetConnected = true;
- return true;
- }
- catch (Exception ex)
- {
- IsNetConnected = false;
- return false;
- }
- }
- private FtpWebRequest OpenRequest(Uri uri, string ftpMethord)
- {
- try
- {
- FtpWebRequest ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpRequest.Credentials = new NetworkCredential(userId, passWord);
- ftpRequest.Method = ftpMethord;
- ftpRequest.UseBinary = true;
- return ftpRequest;
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private FtpWebResponse OpenResponse(Uri uri, string ftpMethord)
- {
- try
- {
- return this.OpenRequest(uri, ftpMethord).GetResponse() as FtpWebResponse;
- }
- catch
- {
- throw new Exception("登录到Ftp服务器失败!");
- }
- }
- #endregion
- /// <summary>
- /// 下载(重命名)
- /// </summary>
- /// <param name="sourceFullPath">下载文件全路径</param>
- /// <param name="targetFullPath">下载到本机全路径(包含文件名)</param>
- /// <returns></returns>
- public bool DownLoadReName(string sourceFullPath, string targetFullPath)
- {
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + sourceFullPath);
- FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.DownloadFile);
- Stream responseStream = downloadResponse.GetResponseStream();
- FileStream fileStream = File.Create(targetFullPath);
- byte[] buffer = new byte[1024];
- int bytesRead = 0;
- while (true)
- {
- bytesRead = responseStream.Read(buffer, 0, buffer.Length);
- if (bytesRead == 0)
- break;
- fileStream.Write(buffer, 0, bytesRead);
- }
- fileStream.Close();
- responseStream.Close();
- return true;
- }
- catch
- {
- throw new Exception("获取下载文件失败!");
- }
- }
- /// <summary>
- /// 下载(按原名直接)
- /// </summary> www.jbxue.com
- /// <param name="loadFullPath">下载文件的全路径</param>
- /// <param name="targePath">下载到指定的地址(E:/)</param>
- /// <returns></returns>
- public bool DownLoadNotReName(string sourceFullPath, string targePath)
- {
- try
- {
- string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/"));
- if (!Directory.Exists(targePath))//不存在就创建文件夹
- {
- Directory.CreateDirectory(targePath);
- }
- return DownLoadReName(sourceFullPath, targePath + fileName);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- /// <summary>
- /// 文件上传
- /// </summary>
- /// <param name="sourceFullPath">要上传文件的地址(G:/Ftp.txt)</param>
- /// <param name="targetPath">服务器端地址(temp)</param>
- /// <returns></returns>
- public bool UploadFile(string sourceFullPath, string targetPath)
- {
- try
- {
- string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("\\") + 1);
- //检查路径
- Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + targetPath + "/" + Uri.EscapeDataString(fileName));
- FtpWebRequest request = this.OpenRequest(uri, WebRequestMethods.Ftp.UploadFile);
- Stream requestStream = request.GetRequestStream();
- FileStream fileStream = new System.IO.FileStream(sourceFullPath, FileMode.Open);
- byte[] buffer = new byte[2048];
- int bytesRead;
- while (true)
- {
- bytesRead = fileStream.Read(buffer, 0, buffer.Length);
- if (bytesRead == 0)
- break;
- requestStream.Write(buffer, 0, bytesRead);
- }
- requestStream.Close();
- request.GetResponse();
- fileStream.Close();
- return true;
- }
- catch (Exception)
- {
- return false;
- }
- }
- /// <summary>
- /// 获取目录文件详细信息
- /// </summary>
- /// <param name="ServerPath">远端的地址</param>
- /// <param name="WRMethods">
- /// <returns></returns>
- ///
- private string[] GetFileList(string ServerPath, string WRMethods)
- {
- StringBuilder result = new StringBuilder();
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + ServerPath);
- FtpWebResponse downloadResponse = OpenResponse(uri, WRMethods);
- Stream responseStream = downloadResponse.GetResponseStream();
- StreamReader reader = new StreamReader(responseStream, System.Text.Encoding.Default);
- string line = reader.ReadLine();
- while (line != null)
- {
- result.Append(line);
- result.Append("\n");
- line = reader.ReadLine();
- }
- if (result.ToString() != "")
- {
- result.Remove(result.ToString().LastIndexOf("\n"), 1);
- }
- reader.Close();
- downloadResponse.Close();
- return result.ToString().Split('\n');
- }
- catch (Exception ex)
- {
- throw new Exception("获取文件列表失败,原因: " + ex.Message);
- }
- }
- /// <summary>
- /// 获得文件列表
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- ///
- public string[] GetFileNameList(string dirName)
- {
- string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
- List<string> strList = new List<string>();
- if (drectory.Length > 0)
- {
- foreach (string str in drectory)
- {
- if (str.Trim().Length == 0)
- continue;
- //会有两种格式的详细信息返回
- //一种包含<DIR>
- //一种第一个字符串是drwxerwxx这样的权限操作符号
- //现在写代码包容两种格式的字符串
- if (!str.Trim().Contains("<DIR>"))
- {
- strList.Add(str.Substring(str.LastIndexOf(":") + 4).Trim()) ;
- }
- else
- {
- if (str.Trim().Substring(0, 1).ToUpper() != "D")
- {
- strList.Add(str.Substring(str.LastIndexOf(":") + 1).Trim()) ;
- }
- }
- }
- }
- return strList.ToArray();
- }
- /// <summary>
- /// 获得文件明晰
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- public string[] GetFilesDetailList(string dirName)
- {
- return GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
- }
- /// <summary>
- /// 获取目录列表
- /// </summary>
- /// <param name="dirName">远端的地址</param>
- /// <returns></returns>
- ///
- public string[] GetDirectoryList(string dirName)
- {
- string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
- List<string> strList = new List<string>();
- if (drectory.Length > 0)
- {
- foreach (string str in drectory)
- {
- if (str.Trim().Length == 0)
- continue;
- //会有两种格式的详细信息返回
- //一种包含<DIR>
- //一种第一个字符串是drwxerwxx这样的权限操作符号
- //现在写代码包容两种格式的字符串
- if (str.Trim().Contains("<DIR>"))
- {
- strList.Add(str.Substring(39).Trim());
- }
- else
- {
- if (str.Trim().Substring(0, 1).ToUpper() == "D")
- {
- strList.Add(str.Substring(55).Trim());
- }
- }
- }
- }
- return strList.ToArray();
- }
- /// <summary>
- /// 判断当前目录下指定的子目录是否存在
- /// </summary>
- /// <param name="RemoteDirectoryName">指定的目录名</param>
- public bool DirectoryExist(string rootDir, string RemoteDirectoryName)
- {
- string[] dirList = GetDirectoryList(rootDir);//获取子目录
- if (dirList.Length > 0)
- {
- foreach (string str in dirList)
- {
- if (str.Trim() == RemoteDirectoryName.Trim())
- {
- return true;
- }
- }
- }
- return false;
- }
- /// <summary>
- /// 创建目录
- /// </summary>
- /// <param name="dirName"></param>
- public void MakeDir(string dirName)
- {
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + dirName);
- FtpWebResponse downloadResponse = OpenResponse(uri, WebRequestMethods.Ftp.MakeDirectory);
- downloadResponse.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("创建文件失败,原因: " + ex.Message);
- }
- }
- }
- }
|