编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

C#连接FTP实现文件上传下载

wxchong 2025-02-09 14:29:38 开源技术 10 ℃ 0 评论


一、引用DLL


using System.IO;
using System.Net;

二、创建FTP连接


///   
/// 连接FTP服务器
///   
/// FTP连接地址  
/// 指定FTP连接成功后的当前目录, 如果不指定默认根目录  
/// 用户名  
/// 密码  
public FTPHelper(string FtpServerIP, string FtpRemotePath, string FtpUserID, string FtpPassword)
{
	System.Net.ServicePointManager.DefaultConnectionLimit = 200;


	FtpServerIP = FtpServerIP.Replace("ftp://", "");


	string[] arr = FtpServerIP.Split('/');
	if (arr.Length > 1)
	{
		FtpServerIP = arr[0];
		for (int i = 1; i < arr.Length; i++)
		{
			FtpRemotePath += "/" + arr[i];
		}
		if (FtpRemotePath.Substring(FtpRemotePath.Length - 1) == "/")
		{
			FtpRemotePath = FtpRemotePath.Substring(0, FtpRemotePath.Length - 1);
		}
	}


	ftpServerIP = FtpServerIP;
	ftpRemotePath = FtpRemotePath;
	ftpUserID = FtpUserID;
	ftpPassword = FtpPassword;
	if (string.IsNullOrEmpty(ftpRemotePath))
	{
		ftpURI = "ftp://" + ftpServerIP + "/";
	}
	else
	{
		ftpURI = "ftp://" + ftpServerIP + ftpRemotePath + "/";
	}
	FtpCheckDirectoryExist(ftpRemotePath + "/");
}

三、上传、下载


///   
/// 上传  
///    
public void Upload(string filename)
{
	FileInfo fileInf = new FileInfo(filename);
	FtpWebRequest reqFTP;
	reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
	reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
	reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
	reqFTP.UsePassive = false;
	reqFTP.KeepAlive = true;
	reqFTP.UseBinary = true;
	reqFTP.ContentLength = fileInf.Length;
	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);
			contentLen = fs.Read(buff, 0, buffLength);
		}
		strm.Close();
		fs.Close();
	}
	catch (Exception ex)
	{
		throw new Exception(ex.Message);
	}
}
///   
/// 下载  
///    
public void Download(string filePath, string fileName)
{
	try
	{
		FileInfo fileInf = new FileInfo(fileName);


		FtpWebRequest reqFTP;
		reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileInf.Name));
		reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);


		reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
		reqFTP.UseBinary = true;
		FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
		Stream ftpStream = response.GetResponseStream();


		long cl = response.ContentLength;
		int bufferSize = 2048;
		int readCount;
		byte[] buffer = new byte[bufferSize];
		readCount = ftpStream.Read(buffer, 0, bufferSize);


		FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
		while (readCount > 0)
		{
			outputStream.Write(buffer, 0, readCount);
			readCount = ftpStream.Read(buffer, 0, bufferSize);
		}
		ftpStream.Close();
		outputStream.Close();
		response.Close();
	}
	catch (Exception ex)
	{
		throw new Exception(ex.Message);
	}
}

四、创建目录


/// 
/// 判断文件的目录是否存,不存则创建 
/// 
/// 
public void FtpCheckDirectoryExist(string destFilePath)
{
	try
	{
		string fullDir = FtpParseDirectory(destFilePath);
		string[] dirs = fullDir.Split('/');
		string curDir = "/";
		for (int i = 0; i < dirs.Length; i++)
		{
			string dir = dirs[i];
			//如果是以/开始的路径,第一个为空    
			if (dir != null && dir.Length > 0)
			{
				try
				{
					curDir += dir + "/";
					Uri uri = new Uri("ftp://" + ftpServerIP + curDir);


					if (!DirectoryIsExist(uri, ftpUserID, ftpPassword))
					{
						FtpMakeDir(curDir);
					}
				}
				catch (Exception e)
				{
					throw new Exception(e.Message);
				}
			}
		}
	}
	catch (Exception ex)
	{
		throw new Exception("FtpCheckDirectoryExist异常" + ex.Message);
	}


}


/// 
/// 截图字符
/// 
/// 
/// 
public string FtpParseDirectory(string destFilePath)
{
	return destFilePath.Substring(0, destFilePath.LastIndexOf("/"));
}


/// 
/// 创建目录
/// 
/// 
///   
public Boolean FtpMakeDir(string localFile)
{
	FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + localFile);
	req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
	req.Method = WebRequestMethods.Ftp.MakeDirectory;
	try
	{
		FtpWebResponse response = req.GetResponse() as FtpWebResponse;
		response.Close();
	}
	catch (Exception)
	{
		req.Abort();
		return false;
	}
	req.Abort();
	return true;
}


//文件是否存在
public bool DirectoryIsExist(Uri pFtpServerIP, string pFtpUserID, string pFtpPW)
{
	string[] value = GetFileList(pFtpServerIP, pFtpUserID, pFtpPW);
	if (value == null)
	{
		return false;
	}
	else
	{
		return true;
	}
}


//获取文件集
public string[] GetFileList(Uri pFtpServerIP, string pFtpUserID, string pFtpPW)
{
	StringBuilder result = new StringBuilder();
	try
	{
		FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(pFtpServerIP);
		reqFTP.UseBinary = true;
		reqFTP.Credentials = new NetworkCredential(pFtpUserID, pFtpPW);
		reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;


		WebResponse response = reqFTP.GetResponse();
		StreamReader reader = new StreamReader(response.GetResponseStream());
		string line = reader.ReadLine();
		while (line != null)
		{
			result.Append(line);
			result.Append("\n");
			line = reader.ReadLine();
		}
		reader.Close();
		response.Close();
		return result.ToString().Split('\n');
	}
	catch(Exception e)
	{
		return null;
	}
}

五、删除文件


///   
/// 删除文件  
///   
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);
	}
}
  • C#实现UDP通讯
  • C#实现TCP通讯
  • C#实现西门子S7-1200、200 SMART PLC之间通信
  • C#实现WebApi接口数据传输加密方案
  • C#操作Redis实现读写、订阅发布功能
  • C# WinForm实现百家号自动登录上传视频功能
  • JAVA实现海康车牌识别一体机语音播报、led内容显示



Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表