C# FTP操作(上传、下载等……)| Id | Title | DateAdded | SourceUrl | PostType | Body | BlogId | Description | DateUpdated | IsMarkdown | EntryName | CreatedTime | IsActive | AutoDesc | AccessPermission |
| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------| -------------|
| 17285550| C# FTP操作(上传、下载等……)| 2023-04-04T10:24:00| | BlogPost|
目录
判断FTP连接
FTP文件上传
FTP文件下载
删除指定FTP文件
删除指定FTP文件夹
获取FTP上文件夹/文件列表
创建文件夹
获取指定FTP文件大小
更改指定FTP文件名称
移动指定FTP文件
应用示例
判断FTP连接
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(); </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">true</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex) { </span><span style="color: #0000ff;">return</span> <span style="color: #0000ff;">false</span><span style="color: #000000;">; } }</span></pre>
FTP文件上传
参数localfile为要上传的本地文件,ftpfile为上传到FTP的文件名称,ProgressBar为显示上传进度的滚动条,适用于WinForm。若应用于控制台程序,只要重写该函数,将参数ProgressBar去掉即可,同时将函数实现里所有涉及ProgressBar的地方都删掉。
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); } }
FTP文件下载
参数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;</span><span style="color: #0000ff;">int</span><span style="color: #000000;"> readCount; </span><span style="color: #0000ff;">byte</span>[] buffer = <span style="color: #0000ff;">new</span> <span style="color: #0000ff;">byte</span><span style="color: #000000;">[bufferSize]; readCount </span>= ftpStream.Read(buffer, <span style="color: #800080;">0</span><span style="color: #000000;">, bufferSize); </span><span style="color: #0000ff;">while</span> (readCount > <span style="color: #800080;">0</span><span style="color: #000000;">) { outputStream.Write(buffer, </span><span style="color: #800080;">0</span><span style="color: #000000;">, readCount); </span><span style="color: #0000ff;">if</span> (pb != <span style="color: #0000ff;">null</span><span style="color: #000000;">) { </span><span style="color: #0000ff;">if</span> (pb.Value !=<span style="color: #000000;"> pb.Maximum) pb.Value </span>= pb.Value + <span style="color: #800080;">1</span><span style="color: #000000;">; } readCount </span>= ftpStream.Read(buffer, <span style="color: #800080;">0</span><span style="color: #000000;">, bufferSize); System.Windows.Forms.Application.DoEvents(); } </span><span style="color: #0000ff;">if</span> (pb != <span style="color: #0000ff;">null</span><span style="color: #000000;">) pb.Value </span>=<span style="color: #000000;"> pb.Maximum; System.Windows.Forms.Application.DoEvents(); ftpStream.Close(); outputStream.Close(); response.Close(); } </span><span style="color: #0000ff;">catch</span><span style="color: #000000;"> (Exception ex) { File.Delete(localfilename); </span><span style="color: #0000ff;">throw</span> <span style="color: #0000ff;">new</span><span style="color: #000000;"> Exception(ex.Message); } } }</span></pre>
删除指定FTP文件
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); } }
删除指定FTP文件夹
public void RemoveDirectory(string urlpath) { try { string uri = ftpURI + urlpath; FtpWebRequest reqFTP; reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory; 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); } }
获取FTP上文件夹/文件列表
ListType=1代表获取文件列表,ListType=2代表获取文件夹列表,ListType=3代表获取文件和文件夹列表。
Detail=true时获文件或文件夹详细信息,Detail=false时只获取文件或文件夹名称。
Keyword是只需list名称包含Keyword的文件或文件夹,若要list所有文件或文件夹,则该参数为空。若ListType=3,则该参数无效。
————————————————
版权声明:本文为CSDN博主「只会搬运的小菜鸟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011465910/article/details/126563124
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());//中文文件名 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); } }
获取指定FTP文件大小
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; }
更改指定FTP文件名称
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);
}
}
移动指定FTP文件
移动FTP文件其实就是重命名文件,只要将目标文件指定一个新的FTP地址就可以了。我没用过,不知道是否可行,因为C++是这么操作的。
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}
应用示例
将上面的内容打包到下面这个FTP类中,就可以在你的业务代码中调用了。
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
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 + "/";
}
//把上面介绍的那些方法都放到下面
}
}
举个例子:
using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
uusing TECSharpFunction;
namespace FTPTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Public void FTP_Test()
{
FTPHelper ftpClient = new FTPHelper("192.168.1.1",@"/test","Test","Test");
ftpClient.Download("test.txt", "test1.txt", progressBar1);
}
}
}
好了,就这样吧!
————————————————
版权声明:本文为CSDN博主「只会搬运的小菜鸟」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/u011465910/article/details/126563124