Files
2026-05-29 09:34:04 +08:00

332 lines
13 KiB
C#
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
using System.Windows.Forms;
namespace TECSharpFunction
{
/// <summary>
/// FTP操作
/// </summary>
public class FTPHelper
{
#region FTPConfig
string ftpURI;
string ftpUserID;
string ftpServerIP;
string ftpPassword;
string ftpRemotePath;
#endregion
/// <summary>
/// 连接FTP服务器
/// </summary>
/// <param name="FtpServerIP">FTP连接地址</param>
/// <param name="FtpRemotePath">指定FTP连接成功后的当前目录, 如果不指定即默认为根目录</param>
/// <param name="FtpUserID">用户名</param>
/// <param name="FtpPassword">密码</param>
public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
public bool CheckFtp()
{
try
{
FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
// ftp用户名和密码
ftprequest.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftprequest.Method = WebRequestMethods.Ftp.ListDirectory;
ftprequest.Timeout = 3000;
FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
ftpResponse.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
// 参数localfile为要上传的本地文件ftpfile为上传到FTP的文件名称ProgressBar为显示上传进度的滚动条适用于WinForm。若应用于控制台程序只要重写该函数将参数ProgressBar去掉即可同时将函数实现里所有涉及ProgressBar的地方都删掉。
//————————————————
//版权声明本文为CSDN博主「只会搬运的小菜鸟」的原创文章遵循CC 4.0 BY-SA版权协议转载请附上原文出处链接及本声明。
//原文链接https://blog.csdn.net/u011465910/article/details/126563124
public void Upload(string localfile, string ftpfile, System.Windows.Forms.ProgressBar pb)
{
FileInfo fileInf = new FileInfo(localfile);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfile));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
if (pb != null)
{
pb.Maximum = Convert.ToInt32(reqFTP.ContentLength / 2048);
pb.Maximum = pb.Maximum + 1;
pb.Minimum = 0;
pb.Value = 0;
}
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = fileInf.OpenRead();
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
if (pb != null)
{
if (pb.Value != pb.Maximum)
pb.Value = pb.Value + 1;
}
contentLen = fs.Read(buff, 0, buffLength);
System.Windows.Forms.Application.DoEvents();
}
if (pb != null)
pb.Value = pb.Maximum;
System.Windows.Forms.Application.DoEvents();
strm.Close();
fs.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
//参数localfilename为将下载到本地的文件名称ftpfilename为要下载的FTP上文件名称
// ProcessBar为用于显示下载进度的进度条。该函数用于WinForm若用于控制台只要重写该函数删除所有涉及ProcessBar的代码即可。
public void Download(string localfilename, string ftpfileName, System.Windows.Forms.ProgressBar pb)
{
long fileSize = GetFileSize(ftpfileName);
if (fileSize > 0)
{
if (pb != null)
{
pb.Maximum = Convert.ToInt32(fileSize / 2048);
pb.Maximum = pb.Maximum + 1;
pb.Minimum = 0;
pb.Value = 0;
}
try
{
FileStream outputStream = new FileStream(localfilename, FileMode.Create);
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
if (pb != null)
{
if (pb.Value != pb.Maximum)
pb.Value = pb.Value + 1;
}
readCount = ftpStream.Read(buffer, 0, bufferSize);
System.Windows.Forms.Application.DoEvents();
}
if (pb != null)
pb.Value = pb.Maximum;
System.Windows.Forms.Application.DoEvents();
ftpStream.Close();
outputStream.Close();
response.Close();
}
catch (Exception ex)
{
File.Delete(localfilename);
//throw new Exception(ex.Message);
}
}
}
public void Delete(string fileName)
{
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
reqFTP.KeepAlive = 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);
}
}
//ListType=1代表获取文件列表ListType=2代表获取文件夹列表ListType=3代表获取文件和文件夹列表。
//Detail=true时获文件或文件夹详细信息Detail=false时只获取文件或文件夹名称。
//Keyword是只需list名称包含Keyword的文件或文件夹若要list所有文件或文件夹则该参数为空。若ListType=3则该参数无效。
//————————————————
//版权声明本文为CSDN博主「只会搬运的小菜鸟」的原创文章遵循CC 4.0 BY-SA版权协议转载请附上原文出处链接及本声明。
public List<string> GetFileDirctoryList(int ListType, bool Detail, string Keyword)
{
List<string> strs = new List<string>();
try
{
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
if (Detail)
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
else
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.Default);//中文文件名
string line = reader.ReadLine();
while (line != null)
{
if (ListType == 1)
{
if (line.Contains("."))
{
if (Keyword.Trim() == "*.*" || Keyword.Trim() == "")
{
strs.Add(line);
}
else if (line.IndexOf(Keyword.Trim()) > -1)
{
strs.Add(line);
}
}
}
else if (ListType == 2)
{
if (!line.Contains("."))
{
if (Keyword.Trim() == "*" || Keyword.Trim() == "")
{
strs.Add(line);
}
else if (line.IndexOf(Keyword.Trim()) > -1)
{
strs.Add(line);
}
}
}
else if (ListType == 3)
{
strs.Add(line);
}
line = reader.ReadLine();
}
reader.Close();
response.Close();
return strs;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void MakeDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public long GetFileSize(string ftpfileName)
{
long fileSize = 0;
try
{
FtpWebRequest reqFTP;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + ftpfileName));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return fileSize;
}
public void ReName(string currentFilename, string newFilename)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + currentFilename));
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}
}
}