123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456 |
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Text;
- using System.IO;
- namespace MOTINOVA_Motor_Factory_Set
- {
- public class ftp
- {
- string serverIP;
- string serverPort;
- string userId;
- string passWord;
- public bool IsNetConnected = false;
- /// <summary>
- /// 配置网络
- /// </summary>
- /// <param name="serverIP"></param>
- /// <param name="serverPort"></param>
- /// <param name="userId"></param>
- /// <param name="passWord"></param>
- public void FtpOption(string serverIP, string serverPort, string userId, string passWord)
- {
- this.serverIP = serverIP;
- this.serverPort = serverPort;
- this.userId = userId;
- this.passWord = passWord;
- }
- /// <summary>
- /// 检查网络
- /// </summary>
- /// <returns>bool</returns>
- 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;
- FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
- ftpResponse.Close();
- IsNetConnected = true;
- return true;
- }
- catch (Exception)
- {
- IsNetConnected = false;
- return false;
- }
- }
- /// <summary>
- /// 文件上传
- /// </summary>
- /// <param name="sourceFullPath">要上传文件全名</param>
- /// <param name="targetPath">服务器端地址(temp)</param>
- /// <returns></returns>
- public bool UploadFile(string sourceFullPath, string targetPath)
- {
- FtpWebRequest reqFTP = null;
- FileStream fs = null;
- Stream strm = null;
- FileInfo fileInf = new FileInfo(sourceFullPath);
- string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("\\") + 1);
- //远端存在该文件时,先删除
- if (FileExist(targetPath, fileName))
- {
- DeleteFile(targetPath + "/" + fileName);
- }
- Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + targetPath + "/" + Uri.EscapeDataString(fileName));
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.Credentials = new NetworkCredential(userId, passWord);
- reqFTP.KeepAlive = false;
- reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
- reqFTP.UseBinary = true;
- reqFTP.UsePassive = false;
- reqFTP.ContentLength = fileInf.Length;
- byte[] buff = new byte[2048];
- int contentLen = 0;
- fs = fileInf.OpenRead();
- try
- {
- strm = reqFTP.GetRequestStream();
- while ((contentLen = fs.Read(buff, 0, buff.Length)) != 0)
- {
- strm.Write(buff, 0, contentLen);
- }
- fs.Close();
- strm.Close();
- return true;
- }
- catch (Exception ex)
- {
- fs.Close();
- strm.Close();
- throw new Exception("上传文件失败,原因: " + ex.Message);
- }
- }
- /// <summary>
- /// 文件下载
- /// </summary>
- /// <param name="filePath">文件本地存放路径</param>
- /// <param name="serverPath">远端文件路径</param>
- /// <param name="fileName">文件名</param>
- /// <returns>bool</returns>
- public bool DownloadFile(string sourceFullPath, string targetFullPath)
- {
- FtpWebRequest ftpRequest = null;
- FileStream outputStream = null;
- FtpWebResponse response = null;
- Stream ftpStream = null;
- try
- {
- string fileName = sourceFullPath.Substring(sourceFullPath.LastIndexOf("/"));
- outputStream = new FileStream(targetFullPath + fileName, FileMode.Create);
- Uri uri = new Uri("ftp://" + serverIP + "/" + sourceFullPath);
- ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
- ftpRequest.UseBinary = true;
- ftpRequest.UsePassive = false;
- ftpRequest.Proxy = null;
- ftpRequest.Credentials = new NetworkCredential(userId, passWord);
- response = (FtpWebResponse)ftpRequest.GetResponse();
- ftpStream = response.GetResponseStream();
- int readCount = 0;
- byte[] buffer = new byte[2048];
- while ((readCount = ftpStream.Read(buffer, 0, buffer.Length)) > 0)
- {
- outputStream.Write(buffer, 0, readCount);
- }
- outputStream.Close();
- ftpStream.Close();
- response.Close();
- return true;
- }
- catch (Exception ex)
- {
- outputStream.Close();
- ftpStream.Close();
- response.Close();
- throw new Exception("下载文件失败,原因: " + ex.Message);
- }
- }
- /// <summary>
- /// 删除文件
- /// </summary>
- /// <param name="fileName"></param>
- public void DeleteFile(string fileName)
- {
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + fileName);
- FtpWebRequest reqFTP;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.Credentials = new NetworkCredential(userId, passWord);
- reqFTP.KeepAlive = false;
- reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
- reqFTP.UsePassive = false;
- string result = String.Empty;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- long size = response.ContentLength;
- Stream datastream = response.GetResponseStream();
- StreamReader sr = new StreamReader(datastream);
- result = sr.ReadToEnd();
- sr.Close();
- datastream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("文件删除失败!" + ex.Message);
- }
- }
- /// <summary>
- /// 删除文件夹
- /// </summary>
- /// <param name="folderName"></param>
- public void RemoveDirectory(string folderName)
- {
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + folderName);
- FtpWebRequest reqFTP;
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.Credentials = new NetworkCredential(userId, passWord);
- reqFTP.KeepAlive = false;
- reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
- reqFTP.UsePassive = false;
- string result = String.Empty;
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- long size = response.ContentLength;
- Stream datastream = response.GetResponseStream();
- StreamReader sr = new StreamReader(datastream);
- result = sr.ReadToEnd();
- sr.Close();
- datastream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("文件夹删除失败!" + ex.Message);
- }
- }
- /// <summary>
- /// 获取当前目录下明细(包含文件和文件夹)
- /// </summary>
- /// <param name="ServerPath">远端的地址</param>
- /// <param name="WRMethods">
- /// <returns></returns>
- ///
- private string[] GetFileList(string ServerPath, string WRMethods)
- {
- StringBuilder result = null;
- FtpWebRequest ftp = null;
- WebResponse response = null;
- StreamReader reader = null;
- try
- {
- result = new StringBuilder();
- Uri uri = new Uri("ftp://" + serverIP + "/" + ServerPath);
- ftp = (FtpWebRequest)FtpWebRequest.Create(uri);
- ftp.Credentials = new NetworkCredential(userId,passWord);
- ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
- ftp.UsePassive = false;
- response = ftp.GetResponse();
- reader = new StreamReader(response.GetResponseStream(), 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();
- response.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="rootDir">远端目录</param>
- /// <param name="fileName">指定文件</param>
- /// <returns></returns>
- public bool FileExist(string rootDir, string fileName)
- {
- string[] fileList = GetFileNameList(rootDir);
- if (fileList.Length > 0)
- {
- foreach (string file in fileList)
- {
- if (file.Substring(file.LastIndexOf("/") + 1) == fileName)
- {
- return true;
- }
- }
- }
- return false;
- }
- /// <summary>
- /// 创建目录
- /// </summary>
- /// <param name="dirName"></param>
- public void MakeDir(string dirName)
- {
- FtpWebRequest reqFTP;
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + dirName);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
- reqFTP.UseBinary = true;
- reqFTP.UsePassive = false;
- reqFTP.Credentials = new NetworkCredential(userId,passWord);
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- ftpStream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("创建文件失败,原因: " + ex.Message);
- }
- }
- /// <summary>
- /// 重命名
- /// </summary>
- /// <param name="currentFilename"></param>
- /// <param name="newFilename"></param>
- public void ReName(string currentFilename, string newFilename)
- {
- FtpWebRequest reqFTP;
- try
- {
- Uri uri = new Uri("ftp://" + serverIP + "/" + currentFilename);
- reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
- reqFTP.Method = WebRequestMethods.Ftp.Rename;
- reqFTP.RenameTo = newFilename;
- reqFTP.UseBinary = true;
- reqFTP.UsePassive = false;
- reqFTP.Credentials = new NetworkCredential(userId,passWord);
- FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
- Stream ftpStream = response.GetResponseStream();
- ftpStream.Close();
- response.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("FtpHelper ReName Error --> " + ex.Message);
- }
- }
- /// <summary>
- /// 移动文件
- /// </summary>
- /// <param name="currentFilename"></param>
- /// <param name="newFilename"></param>
- public void MovieFile(string currentFilename, string newDirectory)
- {
- ReName(currentFilename, newDirectory);
- }
- }
- }
|