20240301_JSEQ_upperpc/JiangsuEarthquake_test/JiangsuEarthquake/Models/FTP/FTPConnectModel.cs
XuMin 748090f317 修改部分:
1 地震仪告警记录中故障次数隐藏;电力载波机和光电交换机的供电状态隐藏;
2 除漏水和保护板事件的数据按照浮点数解析,别的按照整数解析;
3 解决TCP Server和Client存在的问题,包括无法监测到客户端连接,无法监测到服务端断开等问题;
2024-08-13 14:35:33 +08:00

522 lines
19 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 Google.Protobuf;
using HandyControl.Data;
using JiangsuEarthquake.Common;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using OperationResult = JiangsuEarthquake.Common.OperationResult;
using HandyControl.Tools.Extension;
using System.Windows.Forms;
using System.Collections.ObjectModel;
namespace JiangsuEarthquake.Models.FTP
{
public class FTPConnectModel : NotifyBase
{
#region Define
private string ip;
/// <summary>
/// IP
/// </summary>
public string IP
{
get { return ip; }
set { ip = value; this.DoNotify(); }
}
private int port;
/// <summary>
/// 端口
/// </summary>
public int Port
{
get { return port; }
set { port = value; this.DoNotify(); }
}
private string username;
/// <summary>
/// 用户名
/// </summary>
public string UserName
{
get { return username; }
set { username = value; this.DoNotify(); }
}
private string password;
/// <summary>
/// 密码
/// </summary>
public string PassWord
{
get { return password; }
set { password = value; this.DoNotify(); }
}
public string ftpRemotePath; //FTP目标目录
public string Ipath; //目标文件存放路径
private string frpurl;
public string ftpURI //得到的FTPUrL
{
get { return frpurl; }
set { frpurl = value; this.DoNotify(); }
}
public string ftpUrls; //得到相对的Url
#endregion
/// <summary>
/// FTP请求对象
/// </summary>
FtpWebRequest request = null;
/// <summary>
/// FTP响应对象
/// </summary>
FtpWebResponse response = null;
/// <summary>
/// 文件目录
/// </summary>
List<FileMode> fileLists = new List<FileMode>();
/// <summary>
/// 多个消息实体
/// </summary>
List<OperationResult> operationResults = new List<OperationResult>();
/// <summary>
/// 单个消息实体
/// </summary>
OperationResult operationResult = new OperationResult();
#region FTP初始化
/// <summary>
/// 获取FTP的URL
/// </summary>
/// <param name="ftpServerIP"></param>
/// <param name="ftpServerPort"></param>
/// <param name="ftpRemotePath"></param>
/// <param name="ftpUserID"></param>
/// <param name="ftpPassword"></param>
/// <param name="Ipath"></param>
public string getFtpHelper(string ftpServerIP, int ftpServerPort, string ftpRemotePath, string ftpUserID, string ftpPassword, string Ipath)
{
this.IP = ftpServerIP;
this.ftpRemotePath = ftpRemotePath;
this.port = ftpServerPort;
this.Ipath = Ipath;
this.UserName = ftpUserID;
this.PassWord = ftpPassword;
this.ftpUrls = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/";
this.ftpURI = "ftp://" + ftpServerIP + ":" + ftpServerPort + "/" + (string.IsNullOrEmpty(ftpRemotePath) ? "" : ftpRemotePath);
return ftpURI;
}
/// <summary>
/// 建立FTP链接,返回响应对象
/// </summary>
/// <param name="uri">FTP地址</param>
/// <param name="ftpMethod">操作命令</param>
/// <returns></returns>
private FtpWebResponse Open(Uri uri, string ftpMethod)
{
request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Method = ftpMethod;
request.UseBinary = true;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(this.UserName, this.PassWord);
return (FtpWebResponse)request.GetResponse();
}
/// <summary>
/// 建立FTP链接,返回请求对象
/// </summary>
/// <param name="uri">FTP地址</param>
/// <param name="ftpMethod">操作命令</param>
private FtpWebRequest OpenRequest(Uri uri, string ftpMethod)
{
request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = ftpMethod;
request.UseBinary = true;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(this.UserName, this.PassWord);
return request;
}
/// <summary>
/// 建立FTP链接,返回请求对象
/// </summary>
/// <param name="uri">FTP地址</param>
/// <param name="ftpMethod">操作命令</param>
private FtpWebRequest FTPRequest(Uri uri, string ftpMethod)
{
request = (FtpWebRequest)WebRequest.Create(uri);
request.Method = ftpMethod;
request.UseBinary = true;
request.KeepAlive = false;
request.Credentials = new NetworkCredential(UserName, PassWord);
return request;
}
/// <summary>
/// 建立FTP链接,返回响应对象
/// </summary>
/// <param name="uri">请求的URL</param>
/// <param name="ftpMethod">请求的方法</param>
/// <returns></returns>
private FtpWebResponse FTPResponse(Uri uri, string ftpMethod)
{
try
{
request = (FtpWebRequest)FtpWebRequest.Create(uri);
request.Method = ftpMethod;
request.UseBinary = true;
request.Timeout = 1000;
request.KeepAlive = false; //保持接,其他方法关闭
request.Credentials = new NetworkCredential(UserName, PassWord);
return (FtpWebResponse)request.GetResponse();
}
catch
{
return null;
}
}
/// <summary>
/// 析构函数关闭连接如果不了解析构函数可以去网上查找C#析构函数
/// </summary>
~FTPConnectModel()
{
if (response != null)
{
response.Close();
response = null;
}
if (request != null)
{
request.Abort();
request = null;
}
}
#endregion
#region
/// <summary>
/// 列出当前目录的所有一级子目录
/// </summary>
public List<FTPModel> ListDirectories()
{
try
{
var listAll = ListFilesAndDirectories();
var listFile = listAll.Where(m => m.IsDirectory == true).ToList();
return listFile;
}
catch
{
return null;
}
}
/// <summary>
/// 列出当前目录的所有文件
/// </summary>
public List<FTPModel> ListFiles()
{
try
{
var listAll = ListFilesAndDirectories();
var listFile = listAll.Where(m => m.IsDirectory == false).ToList();
return listFile;
}
catch
{
return null;
}
}
#endregion
#region
//public static Regex FtpListDirectoryDetailsRegex = new Regex(@".*(?<month>(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec))\s*(?<day>[0-9]*)\s*(?<yearTime>([0-9]|:)*)\s*(?<fileName>.*)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
//public static Regex FtpListDirectoryDetailsRegexYear = new Regex(@"\b\d{4}\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
/// <summary>
/// 获取当前目录一级字目录和文件信息
/// </summary>
/// <param name="IsOnlyDir">是否只获取目录</param>
/// <returns></returns>
public List<FTPModel> ListFilesAndDirectories()
{
try
{
var fileList = new List<FTPModel>();
response = FTPResponse(new Uri(ftpURI), WebRequestMethods.Ftp.ListDirectoryDetails);
if (response == null)
return null;
using (var stream = response.GetResponseStream())
{
using (var sr = new StreamReader(stream))
{
string line = null;
int index = 1;
while ((line = sr.ReadLine()) != null)
{
var parts = line.Split(new[] { ' ' }, 9, StringSplitOptions.RemoveEmptyEntries);
string fmsgTime;
if (IsAllDigits(parts[7]))
fmsgTime = Convert.ToDateTime(parts[7] + parts[5] + parts[6]).ToString("yyyy/MM/dd");
else
fmsgTime = Convert.ToDateTime(DateTime.Now.Year.ToString() + parts[5] + parts[6]).ToString("yyyy/MM/dd");
DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
dtFormat.ShortDatePattern = "yyyy/MM/dd";
var fileInfo = new FTPModel
{
Index = index++,
FileName = parts[8],
FileSize = parts[4] == "4096" ? "" : parts[4] + "Bytes",
CreateTime = Convert.ToDateTime(fmsgTime, dtFormat),
FilePath = ftpRemotePath + "/" + parts[8],
IsDirectory = line.StartsWith('d') ? true : false
};
fileList.Add(fileInfo);
//MatchCollection matchYear = FtpListDirectoryDetailsRegexYear.Matches(line);
//Match match = FtpListDirectoryDetailsRegex.Match(line);
//string month = match.Groups["month"].Value;
//string day = match.Groups["day"].Value;
////string yearTime = match.Groups["yearTime"].Value;
//string fileName = match.Groups["fileName"].Value;
//string size = matchYear[0].Value;
//string year = "";
//foreach (Match ma in matchYear)
//{
// if (int.Parse(ma.Value) >= 2000 && int.Parse(ma.Value) <= 2050)
// year = ma.Value;
//}
//if (year == "")
// year = DateTime.Now.Year.ToString();
//string fmsgTime = Convert.ToDateTime(year + month + day).ToString("yyyy/MM/dd");
//DateTimeFormatInfo dtFormat = new System.Globalization.DateTimeFormatInfo();
//dtFormat.ShortDatePattern = "yyyy/MM/dd";
//FTPModel model = null;
//if (size=="")
//{
// model = new FTPModel()
// {
// CreateTime = Convert.ToDateTime(fmsgTime, dtFormat),
// FileName = fileName,
// FilePath = ftpRemotePath + "/" + fileName,
// IsDirectory = true
// };
//}
//else
//{
// model = new FTPModel()
// {
// CreateTime = Convert.ToDateTime(fmsgTime, dtFormat),
// FileName = fileName,
// FileSize= size,
// FilePath = ftpRemotePath + "/" + fileName,
// IsDirectory = false
// };
//}
//if (line.StartsWith('d')) //代表是文件夹
//{
// model.IsDirectory = true;
//}
////else if (line.StartsWith('l'))
////{
//// //model.IsDirectory = null;
////}
//else if (line.StartsWith('-') || line.StartsWith('l'))
//{
// model.IsDirectory = false;
//}
//fileList.Add(model);
}
}
}
return fileList;
}
catch
{
return null;
}
}
/// <summary>
/// 判断字符串是否全是数字
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static bool IsAllDigits(string str)
{
return str.All(char.IsDigit);
}
/// <summary>
/// 下载
/// </summary>
/// <param name="saveFilePath">下载后的保存路径</param>
/// <param name="downloadFileName">要下载的文件名</param>
public void Download(string saveFilePath, string downloadFileName)
{
try
{
using (FileStream outputStream = new FileStream(saveFilePath + "\\" + downloadFileName, FileMode.Create))
{
response = Open(new Uri(ftpURI + downloadFileName), WebRequestMethods.Ftp.DownloadFile);
using (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);
}
}
}
}
catch
{ }
}
/// <summary>
/// 文件上传
/// </summary>
/// <param name="localFilePath">本地文件路径</param>
public void Upload(string localFilePath)
{
try
{
FileInfo fileInf = new FileInfo(localFilePath);
request = OpenRequest(new Uri(ftpURI + fileInf.Name), WebRequestMethods.Ftp.UploadFile);
request.ContentLength = fileInf.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
using (var fs = fileInf.OpenRead())
{
using (var strm = request.GetRequestStream())
{
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
}
}
}
catch { }
}
/// <summary>
/// 删除文件
/// </summary>
/// <param name="remoteFileName">要删除的文件名</param>
public void DeleteFile(string remoteFileName)
{
response = Open(new Uri(ftpURI + remoteFileName), WebRequestMethods.Ftp.DeleteFile);
}
/// <summary>
/// 删除目录(包括下面所有子目录和子文件)
/// </summary>
/// <param name="remoteDirectoryName">要删除的带路径目录名如web/test</param>
/*
* 例删除test目录
FTPHelper helper = new FTPHelper("x.x.x.x", "web", "user", "password");
helper.RemoveDirectory("web/test");
*/
public void RemoveDirectory(string remoteDirectoryName)
{
GotoDirectory(remoteDirectoryName, true);
var listAll = ListFilesAndDirectories();
foreach (var m in listAll)
{
if (m.IsDirectory)
RemoveDirectory(m.FilePath);
else
DeleteFile(m.FileName);
}
GotoDirectory(remoteDirectoryName, true);
response = Open(new Uri(ftpURI), WebRequestMethods.Ftp.RemoveDirectory);
}
/// <summary>
/// 切换当前目录
/// </summary>
/// <param name="IsRoot">true:绝对路径 false:相对路径</param>
public void GotoDirectory(string DirectoryName, bool IsRoot)
{
if (IsRoot)
ftpRemotePath = DirectoryName;
else
ftpRemotePath += "/" + DirectoryName;
ftpURI = "ftp://" + IP + "/" + ftpRemotePath + "/";
}
/// <summary>
/// 判断当前目录下指定的一级子目录是否存在
/// </summary>
/// <param name="RemoteDirectoryName">指定的目录名</param>
public bool IsDirectoryExist(string remoteDirectoryName)
{
var listDir = ListDirectories();
if (listDir.Count(m => m.FileName == remoteDirectoryName) > 0)
return true;
return false;
}
/// <summary>
/// 判断当前目录下指定的子文件是否存在
/// </summary>
/// <param name="RemoteFileName">远程文件名</param>
public bool IsFileExist(string remoteFileName)
{
var listFile = ListFiles();
if (listFile.Count(m => m.FileName == remoteFileName) > 0)
return true;
return false;
}
#endregion
}
}