2024-12-05 11:34:06 +08:00

197 lines
8.5 KiB
C#
Raw 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 Abp.Dependency;
using FluentFTP;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Windows.Interop;
using Yunda.ISAS.DataMonitoringServer.DataAnalysis;
namespace Yunda.SOMS.DataMonitoringServer.FTPHandle
{
public class FtpFile : ISingletonDependency
{
public static string localDirectory = System.Environment.CurrentDirectory + @"\SaveProtection\files\"; // 本地保存文件的路径
#if DEBUG
public string Test()
{
string ftpBaseUrl = "ftp://192.168.1.110"; // FTP 服务器基础路径
string ftpUsername = "root"; // FTP 用户名
string ftpPassword = "root"; // FTP 密码
string filepath = "/nor/root/commcpu/cfg/";
// 调用函数并传入文件名
string fileName = "commdb.sql3"; // 传入的文件名
string localFile = GetFileFromFtp(ftpBaseUrl, filepath, fileName, ftpUsername, ftpPassword);
// 显示结果
Console.WriteLine($"Returned file: {localFile}");
return localFile;
}
#endif
private static Dictionary<string, DateTime> failedDownloadTimestamps = new Dictionary<string, DateTime>();
/// <summary>
/// 从FTP下载文件如果失败则返回本地上次保存的文件
/// </summary>
/// <param name="ftpHost">FTP服务器主机名</param>
/// <param name="username">FTP用户名</param>
/// <param name="password">FTP密码</param>
/// <param name="fileName">要下载的文件名</param>
/// <param name="localDirectory">本地保存路径</param>
/// <returns>返回下载的文件路径或上次保存的文件路径</returns>
public string GetFileFromFtp(string ftpHost, string fileapth, string fileName, string deviceAddr, string username = "root", string password = "root")
{
string localFilePath = Path.Combine(localDirectory, deviceAddr, fileName); // 本地保存文件的完整路径
string remoteFilePath = Path.Combine(fileapth, fileName); // 远程FTP文件的路径
string key = $"{ftpHost}:{remoteFilePath}"; // 用来唯一标识远程文件的键
// 检查是否在上次失败之后的1小时内
if (failedDownloadTimestamps.ContainsKey(key) && DateTime.Now - failedDownloadTimestamps[key] < TimeSpan.FromHours(1))
{
MonitoringEventBus.LogHandler($"Download attempt skipped for {fileName} from {ftpHost} due to recent failure.", "FTP信息");
// 直接返回本地文件如果存在
if (File.Exists(localFilePath))
{
return localFilePath;
}
else
{
return null;
}
}
using (var client = new FtpClient(ftpHost, username, password))
{
try
{
// 连接到FTP服务器
client.Connect();
// 尝试下载文件到本地
if (client.DownloadFile(localFilePath, remoteFilePath) == FtpStatus.Success)
{
MonitoringEventBus.LogHandler($"Successfully downloaded {fileName} from FTP.", "FTP信息");
// 下载成功,删除失败时间户记录
if (failedDownloadTimestamps.ContainsKey(key))
{
failedDownloadTimestamps.Remove(key);
}
return localFilePath; // 下载成功,返回文件路径
}
else
{
// 下载失败,记录失败的时间
failedDownloadTimestamps[key] = DateTime.Now;
// 检查本地是否有之前的文件
if (File.Exists(localFilePath))
{
string msg = $"Download failed. Returning last saved file: {localFilePath}";
MonitoringEventBus.LogHandler(msg, "FTP信息");
return localFilePath; // 返回本地之前保存的文件
}
else
{
string msg = $"Download failed and no local file found for {fileName}.";
MonitoringEventBus.LogHandler(msg, "FTP信息");
return null; // 本地没有文件返回null
}
}
}
catch (Exception ex)
{
// 处理下载时的异常
string msg = $"An error occurred while downloading {fileName} from FTP: {ex.Message}";
MonitoringEventBus.LogHandler(msg, "FTP信息");
// 记录失败的时间
failedDownloadTimestamps[key] = DateTime.Now;
// 检查是否有之前保存的文件
if (File.Exists(localFilePath))
{
return localFilePath; // 返回本地文件
}
else
{
return null; // 如果本地没有文件返回null
}
}
finally
{
if (client.IsConnected)
{
client.Disconnect(); // 确保连接断开
}
}
}
}
public byte[] GetFileFromFtpToMem(string ftpHost, string fileapth, string fileName, string username = "root", string password = "root")
{
string remoteFilePath = Path.Combine(fileapth, fileName); // 远程FTP文件的路径
string key = $"{ftpHost}:{remoteFilePath}"; // 用来唯一标识远程文件的键
// 检查是否在上次失败之后的1小时内
if (failedDownloadTimestamps.ContainsKey(key) && DateTime.Now - failedDownloadTimestamps[key] < TimeSpan.FromHours(1))
{
MonitoringEventBus.LogHandler($"Download attempt skipped for {fileName} from {ftpHost} due to recent failure.", "FTP信息");
return null;
}
using (var client = new FtpClient(ftpHost, username, password))
{
try
{
// 连接到FTP服务器
client.Connect();
// 尝试下载文件到内存
using (var memoryStream = new MemoryStream())
{
if (client.DownloadStream(memoryStream, remoteFilePath))
{
MonitoringEventBus.LogHandler($"Successfully downloaded {fileName} from FTP.", "FTP信息");
// 下载成功,删除失败时间记录
if (failedDownloadTimestamps.ContainsKey(key))
{
failedDownloadTimestamps.Remove(key);
}
return memoryStream.ToArray(); // 下载成功,返回文件的字节数组
}
else
{
// 下载失败,记录失败的时间
failedDownloadTimestamps[key] = DateTime.Now;
string msg = $"Download failed for {fileName} from FTP.";
MonitoringEventBus.LogHandler(msg, "FTP信息");
return null; // 下载失败返回null
}
}
}
catch (Exception ex)
{
// 处理下载时的异常
string msg = $"An error occurred while downloading {fileName} from FTP: {ex.Message}";
MonitoringEventBus.LogHandler(msg, "FTP信息");
// 记录失败的时间
failedDownloadTimestamps[key] = DateTime.Now;
return null; // 如果发生异常返回null
}
finally
{
if (client.IsConnected)
{
client.Disconnect(); // 确保连接断开
}
}
}
}
}
}