上位机开发中有时要与客户的文件服务器进行数据交互。如Mapping文件下载。结果文件上传等。我在项目中就常用到。现在把项目实战代码进行分享一下。
功能列表:连接服务器,下载文件,上传文件,删除服务器文件,获取当前目录下明细(包含文件和文件夹) ,获取FTP文件列表(包括文件夹),获取当前目录下文件列表(不包括文件夹) ,创建文件夹,获取指定文件大小 ,更改文件名,移动文件 ,删除ftpURI目录下指定的文件夹
调用
1.初始化连接
CommonData.FtpServer_MappingFile = new FTPHelper(ftpIPAddress, ftpUser, ftpPw);
2.下载
//url 服务器下载地址
//savefilePath 保存文件目录
//fileName 文件名,只是文件名
CommonData.FtpServer_MappingFile.DownloadByUrl(url, savefilePath, fileName, true);
3.上传
//currentDirectory 本地文件完整路径包括文件名
//ftpUploadFileName FTP服务器完整上传路径包括文件名
CommonData.FtpServer_MappingFile.Upload(currentDirectory, ftpUploadFileName);
代码
/// <summary>
/// ftp帮助类
/// </summary>
public class FTPHelper
{
#region 字段
string ftpURI;
string ftpUserID;
string ftpServerIP;
string ftpPassword;
string ftpRemotePath;
/// <summary>
/// 下载URL
/// </summary>
public string DownloadUrl { get; set; }
#endregion
public string GetFtpURI()
{
return ftpURI;
}
//public FTPHelper() { }
/// <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, bool isFile = false)
{
ftpServerIP = FtpServerIP;
ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
//ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
if (isFile)
{
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath.Replace("\\", "/");
}
}
/// <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 FtpUserID, string FtpPassword)
{
ftpServerIP = FtpServerIP;
//ftpRemotePath = FtpRemotePath;
ftpUserID = FtpUserID;
ftpPassword = FtpPassword;
//ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
ftpURI = "ftp://" + ftpServerIP;//+ "/" + ftpRemotePath + "/";
//if (isFile)
//{
// ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath.Replace("\\", "/");
//}
}
/// <summary>
/// 上传 filename是本地图片的地址
/// </summary>
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.KeepAlive = false;
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);
}
}
/// <summary>
/// 上传
/// </summary>
/// <param name="fileName">是本地文件全路径</param>
/// <param name="ftpUrl"></param>
/// <param name="lmDir"></param>
/// <returns></returns>
public CommonResultModel<string> Upload(string fileName, string ftpUrl)
{
var resultModel = new CommonResultModel<string>();
FileInfo fileInf = null;
FtpWebRequest reqFTP;
Stream strm = null;
FileStream fs = null;
var uploadUrl = string.Empty;
try
{
//ip/指定目录/lotId/pid.csv
uploadUrl = ftpURI + ftpUrl;
resultModel.Data = uploadUrl;
//var ftpDir = uploadUrl.Replace(lmDir, string.Empty);
var ftpDirList = ftpUrl.Split('/').ToList();
ftpDirList = ftpDirList.FindAll(t => t.Length > 0).FindAll(t => !t.Contains("."));
var newDir = ftpURI;
//判断文件夹是否存在
//resultModel.Msg = "Upload 判断文件夹是否存在 ";
//CommonDefine.SaveWorkLogs(resultModel.Msg);
foreach (var item in ftpDirList)
{
//newDir += "/" + item;
var isExists = FolderExists(newDir, item);
newDir += "/" + item;
//resultModel.Msg += "newDir:" + newDir + ",isExists:" + isExists + ",";
//CommonDefine.SaveWorkLogs(resultModel.Msg);
if (!isExists)
{
var makeDirResultModel = MakeDir(newDir);
//CommonDefine.SaveWorkLogs(resultModel.Msg
// + ", MakeDir: IsSucceed=" + makeDirResultModel.IsSucceed + ",msg:" + makeDirResultModel.Msg);
//if (!makeDirResultModel.IsSucceed)
//{
// throw new Exception(makeDirResultModel.Msg);
//}
}
}
fileInf = new FileInfo(fileName);
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uploadUrl));
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.KeepAlive = false;
reqFTP.UseBinary = true;
reqFTP.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
fs = fileInf.OpenRead();
strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
}
catch (Exception ex)
{
//throw new Exception("uploadUrl:" + uploadUrl + ",Message:" + ex.Message);
resultModel.Msg = "异常:" + ex.Message;
}
finally
{
if (strm != null)
{
strm.Close();
}
if (fs != null)
{
fs.Close();
}
}
return resultModel;
}
/// <summary>
/// 下载 filePath是下载到本机的地址fileName是需要下载的文件的名字
/// </summary>
public void Download(string filePath, string fileName, bool isFile = false)
{
try
{
FileStream outputStream = new FileStream(filePath + "\\" + fileName, FileMode.Create);
FtpWebRequest reqFTP;
if (isFile)
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
}
else
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + fileName));
}
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);
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);
}
}
/// <summary>
/// 下载 filePath是下载到本机的地址fileName是需要下载的文件的名字
/// </summary>
/// <param name="ftpFilePath">FTP下载文件的路径(/mapping/xxx)</param>
/// <param name="savefilePath">本地保存文件路径</param>
/// <param name="savefileName">本地保存文件</param>
/// <param name="isFile">是否是文件</param>
public void DownloadByUrl(string ftpFilePath, string savefilePath, string savefileName, bool isFile = false)
{
try
{
FileStream outputStream = new FileStream(savefilePath + "\\" + savefileName, FileMode.Create);
FtpWebRequest reqFTP;
ftpFilePath = ftpFilePath.Replace("\\", "/");
if (isFile)
{
//DownloadUrl = ftpURI;
DownloadUrl = ftpURI + ftpFilePath;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(DownloadUrl));
}
else
{
//var url = ftpURI + "//" + ftpFilePath.Trim().TrimStart('\\').TrimStart('/');
DownloadUrl = ftpURI + ftpFilePath;
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(DownloadUrl));
}
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);
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("DownloadUrl:" + DownloadUrl + ", errorMsg:" + ex.Message);
}
}
/// <summary>
/// 删除服务器的文件 fileName是需要删除的文件的名字
/// </summary>
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);
}
}
/// <summary>
/// 获取当前目录下明细(包含文件和文件夹)
/// </summary>
public string[] GetFilesDetailList()
{
try
{
StringBuilder result = new StringBuilder();
FtpWebRequest ftp;
ftp = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI));
ftp.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
ftp.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = ftp.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
line = reader.ReadLine();
line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
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>
/// 获取FTP文件列表(包括文件夹)
/// </summary>
private List<string> GetAllList(string url)
{
List<string> list = new List<string>();
FtpWebRequest req = (FtpWebRequest)WebRequest.Create(new Uri(url));
req.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
req.Method = WebRequestMethods.Ftp.ListDirectory;
req.UseBinary = true;
req.UsePassive = true;
try
{
using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
{
using (StreamReader sr = new StreamReader(res.GetResponseStream()))
{
string s;
while ((s = sr.ReadLine()) != null)
{
list.Add(s);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return list;
}
/// <summary>
/// 获取当前目录下文件列表(不包括文件夹)
/// </summary>
public List<string> GetFileList(string url)
{
var fileNameList = new List<string>();
//StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
string line = reader.ReadLine();
while (line != null)
{
//rwxrwxr-- 1 1001 1001 4520 Oct 31 2023 AD2300225P1.xml
CommonDefine.SaveWorkLogs("GetFileList() " + line);
//if (line.IndexOf("<DIR>") == -1)
//{
// var fileName = Regex.Match(line, @"[\S]+ [\S]+", RegexOptions.IgnoreCase).Value.Split(' ')[1];
// CommonDefine.SaveWorkLogs("GetFileList()1 fileName:" + fileName);
// result.Append(fileName);
// result.Append("\n");
//}
var textList = line.Split(' ').ToList();
var fileName = textList.LastOrDefault();
//result.Append(fileName);
fileNameList.Add(fileName);
line = reader.ReadLine();
}
//result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
}
catch (Exception ex)
{
//throw (ex);
throw new Exception(ex.Message + ",url:" + url + ",ftpUserID:" + ftpUserID + ",ftpPassword:" + ftpPassword);
}
//return result.ToString().Split('\n');
return fileNameList;
}
/// <summary>
/// 获取当前目录下文件列表(不包括文件夹)
/// </summary>
public List<string> GetFileListByFilePath(string filePath)
{
var fileList = new List<string>();
//var url = ftpURI + "//" + filePath.Trim().TrimStart('\\').TrimStart('/');
var url = ftpURI + filePath.Trim();
try
{
//var fileNameArray = GetFileList(ftpURI + "//" + filePath);
var fileNameArray = GetFileList(url);
if (fileNameArray != null && fileNameArray.Count > 0)
{
fileList = fileNameArray;
}
}
catch (Exception ex)
{
//throw (ex);
throw new Exception("url:" + url + ",errormsg:" + ex.Message);
}
return fileList;
}
/// <summary>
/// 判断当前目录下指定的文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool FileExist(string RemoteFileName)
{
var fileList = GetFileList("*.*");
foreach (string str in fileList)
{
if (str.Trim() == RemoteFileName.Trim())
{
return true;
}
}
return false;
}
/// <summary>
/// 创建文件夹
/// </summary>
public CommonResultModel<string> MakeDir(string ftpDirName)
{
var resultModel = new CommonResultModel<string>();
FtpWebRequest reqFTP;
FtpWebResponse response = null;
try
{
//resultModel.Msg = "MakeDir 1";
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpDirName));
//resultModel.Msg = "MakeDir 2";
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;//创建文件夹
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
//resultModel.Msg = "MakeDir 3";
using (response = (FtpWebResponse)reqFTP.GetResponse())
{
//resultModel.Msg = "MakeDir 4";
Stream ftpStream = response.GetResponseStream();
//resultModel.Msg = "MakeDir 5";
ftpStream.Close();
resultModel.IsSucceed = true;
}
//response.Close();
}
catch (Exception ex)
{
//resultModel.Msg = ex.Message;
throw ex;
}
finally
{
if (response != null)
{
response.Close();
}
}
return resultModel;
}
/// <summary>
/// 判断文件夹是否存在
/// </summary>
/// <param name="ftpServer"></param>
/// <param name="ftpFolder">文件夹</param>
/// <param name="ftpUsername"></param>
/// <param name="ftpPassword"></param>
/// <returns></returns>
public bool FolderExists(string ftpFolder, string findFolder)
{
bool folderExists = false;
string uploadUrl = string.Empty;
try
{
var fileNameList = CommonData.FtpServer_MappingFile.GetAllList(ftpFolder.Trim());
foreach (var item in fileNameList)
{
//this.lbFtpFileNames.Items.Add(item);
//CommonDefine.SaveWorkLogs("判断文件夹是否存在 获取FTP所有文件 " + ftpFolder + ":" + item);
if (item.Contains(findFolder))
{
folderExists = true;
//CommonDefine.SaveWorkLogs("判断文件夹是否存在 获取FTP所有文件 " + ftpFolder + ":" + item + "," + findFolder + "目录存在");
break;
}
}
}
catch (WebException ex)
{
var response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
{
folderExists = false;
}
else
{
// 处理其他异常
}
}
return folderExists;
}
/// <summary>
/// 获取指定文件大小
/// </summary>
public long GetFileSize(string filename)
{
FtpWebRequest reqFTP;
long fileSize = 0;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + filename));
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
Stream ftpStream = response.GetResponseStream();
fileSize = response.ContentLength;
ftpStream.Close();
response.Close();
}
catch (Exception ex)
{ }
return fileSize;
}
/// <summary>
/// 更改文件名
/// </summary>
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)
{ }
}
/// <summary>
/// 移动文件
/// </summary>
public void MovieFile(string currentFilename, string newDirectory)
{
ReName(currentFilename, newDirectory);
}
/// <summary>
/// 切换当前目录
/// </summary>
/// <param name="IsRoot">true:绝对路径 false:相对路径</param>
public void GotoDirectory(string DirectoryName, bool IsRoot)
{
if (IsRoot)
{
ftpRemotePath = DirectoryName;
}
else
{
ftpRemotePath += DirectoryName + "/";
}
ftpURI = "ftp://" + ftpServerIP + "/" + ftpRemotePath + "/";
}
/// <summary>
/// 删除ftpURI目录下指定的文件夹
/// </summary>
public void DeleteDir(string dirName)
{
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpURI + dirName));
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
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);
}
}
}
本文转载自: https://blog.csdn.net/cjh16606260986/article/details/143358753
版权归原作者 StevenChen85 所有, 如有侵权,请联系我们删除。
版权归原作者 StevenChen85 所有, 如有侵权,请联系我们删除。