using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace Welling_Motor_Debug_Tool
{
public class ftp
{
string serverIP;
string serverPort;
string userId, userId_Admin;
string passWord, passWord_Admin;
public bool IsNetConnected = false;
///
/// 配置网络
///
///
///
///
///
public void FtpOption(string serverIP, string serverPort, string userId, string passWord, string userID_Admin, string passWord_Admin)
{
this.serverIP = serverIP;
this.serverPort = serverPort;
this.userId = userId;
this.passWord = passWord;
this.userId_Admin = userID_Admin;
this.passWord_Admin = passWord_Admin;
}
///
/// 检查网络
///
/// bool
public bool CheckFtp()
{
try
{
Uri uri = new Uri(string.Format("ftp://" + serverIP + ":" + serverPort));
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;
}
}
///
/// 文件上传
///
/// 要上传文件全名
/// 服务器端地址(temp)
///
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_Admin, passWord_Admin);
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
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);
return false;
}
}
///
/// 文件下载
///
/// 文件本地存放路径
/// 远端文件路径
/// 文件名
/// bool
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("/") + 1);
if (Directory.Exists(targetFullPath) == false)
Directory.CreateDirectory(targetFullPath);
outputStream = new FileStream(targetFullPath + "\\" + fileName, FileMode.Create);
Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + sourceFullPath);
ftpRequest = (FtpWebRequest)FtpWebRequest.Create(uri);
ftpRequest.Method = WebRequestMethods.Ftp.DownloadFile;
ftpRequest.UseBinary = true;
ftpRequest.UsePassive = true;
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);
return false;
}
}
///
/// 删除文件
///
///
public void DeleteFile(string fileName)
{
try
{
Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + fileName);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.Credentials = new NetworkCredential(userId_Admin, passWord_Admin);
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);
}
}
///
/// 删除文件夹,只能删除空文件夹
///
///
public void RemoveDirectory(string folderName)
{
try
{
Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + folderName);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.Credentials = new NetworkCredential(userId_Admin, passWord_Admin);
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);
}
}
///
/// 删除目录下面的内容
///
///
public void DelDirectoryWithAll(string folderName)
{
try
{
//获取文件列表
string[] fileList = GetFileNameList(folderName);
//先删除所有文件
if (fileList != null && fileList.Length > 0)
{
foreach (string file in fileList)
{
DeleteFile(folderName + "/" + file);
}
}
//获取文件夹
string[] pathList = GetDirectoryList(folderName);
foreach (string path in pathList)
{
if (string.IsNullOrWhiteSpace(path))
continue;
//子目录存在目录递归
if (GetFilesDetailList(folderName + "/" + path) != null && GetFilesDetailList(folderName + "/" + path).Length > 0)
{
DelDirectoryWithAll(folderName + "/" + path);
}
//删除该级目录
RemoveDirectory(folderName + "/" + path);
}
}
catch (Exception ex)
{
throw new Exception("文件夹删除失败!" + ex.Message);
}
}
///
/// 获取当前目录下明细(包含文件和文件夹)
///
/// 远端的地址
///
///
///
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 + ":" + serverPort + "/" + ServerPath);
ftp = (FtpWebRequest)FtpWebRequest.Create(uri);
ftp.Credentials = new NetworkCredential(userId,passWord);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
ftp.UsePassive = true;
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);
}
}
///
/// 获得文件列表
///
///
///
///
public string[] GetFileNameList(string dirName)
{
string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
List strList = new List();
if (drectory.Length > 0)
{
foreach (string str in drectory)
{
if (str.Trim().Length == 0)
continue;
//-rwxrwxrwx开头
if (str.Trim().Substring(0, 1).ToUpper() == "-")
{
strList.Add(str.Substring(str.LastIndexOf(":") + 4).Trim());
}
}
}
return strList.ToArray();
}
///
/// 获取文件夹下明细
///
///
///
public string[] GetFilesDetailList(string dirName)
{
return GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
}
///
/// 获取目录列表
///
/// 远端的地址
///
///
public string[] GetDirectoryList(string dirName)
{
string[] drectory = GetFileList(dirName, WebRequestMethods.Ftp.ListDirectoryDetails);
List strList = new List();
if (drectory.Length > 0)
{
foreach (string str in drectory)
{
if (str.Trim().Length == 0)
continue;
//drwxrwxrwx开头
if (str.Trim().Substring(0, 1) == "d")
{
strList.Add(str.Split(' ')[str.Split(' ').Length - 1].Trim());
}
}
}
return strList.ToArray();
}
///
/// 判断当前目录下指定的子目录是否存在
///
/// 指定的目录名
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;
}
///
/// 判断目录下指定的文件是否存在
///
/// 远端目录
/// 指定文件
///
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;
}
///
/// 创建目录
///
///
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + dirName);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(uri);
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.UsePassive = true;
reqFTP.Credentials = new NetworkCredential(userId_Admin, passWord_Admin);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show("创建文件失败,原因: " + ex.Message);
}
}
///
/// 重命名
///
///
///
public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
try
{
Uri uri = new Uri("ftp://" + serverIP + ":" + serverPort + "/" + 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_Admin, passWord_Admin);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception("FtpHelper ReName Error --> " + ex.Message);
}
}
///
/// 移动文件
///
///
///
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}
}
}