Files
6098/Cowain.Bake.Communication/FTP/FTPUpload.cs

109 lines
3.6 KiB
C#

using Cowain.Bake.Common;
using Cowain.Bake.Common.Core;
using System;
using System.IO;
using System.Threading.Tasks;
using Unity;
using Unity.Resolution;
namespace Cowain.Bake.Communication.FTP
{
public class FTPUpload
{
string _localFolderPath;
string _remoteFolderPath;
FtpHelper ftpClient;
public string Name { get; set; }
public IUnityContainer _unityContainer { get; set; }
public FTPUpload(IUnityContainer unityContainer)
{
_unityContainer = unityContainer;
ftpClient = _unityContainer.Resolve<FtpHelper>(new ParameterOverride("ipAddr","10.19.30.19"), new ParameterOverride("port", 21),
new ParameterOverride("userName", (object)"admin"), new ParameterOverride("password", (object)"123456"));
ftpClient.Connect();
}
public void Stop()
{
ftpClient.Close();
}
public void Start(string src, string desc)
{
_localFolderPath = src;
_remoteFolderPath = desc;
Task.WaitAny();
Task.Run(async () =>
{
while(true)
{
await Task.Delay(1000);
if (Global.AppExit)
{
ftpClient.Close();
return;
}
UploadToFTPService();
}
});
}
//string localFolderPath = @"E:\svn\CutingStack\CuttingStackingMachine\成都蜂巢6074\tex"; //本地要上传的文件位置 (界面可配)
//string remoteFolderPath = "/"; //MOM服务要上传到的位置 (界面可配)
void UploadToFTPService()
{
// 获取文件夹及其子文件夹中的所有文件
string[] files = Directory.GetFiles(_localFolderPath, "*", SearchOption.AllDirectories);
//string[] files = Directory.GetFiles(localFolderPath);
try
{
// 遍历每个文件
foreach (string file in files)
{
if (IsUpload(file))
{
if (ftpClient.UpLoad(file, _remoteFolderPath))
{
SetFileReadAccess(file, true); //上传的文件做标识(设为可读)
}
}
}
}
catch(Exception ex)
{
LogHelper.Instance.Error($"上传文件失败,localFolderPath:{_localFolderPath},remoteFolderPath:{_remoteFolderPath},异常:{ex.Message}");
}
}
//是否上传:可读为假就上传,为真不上传
bool IsUpload(string filePath)
{
return !IsFileReadable(filePath); //默认为假,不可读(可写)
}
//读为可读
public void SetFileReadAccess(string filePath, bool readOnly)
{
FileInfo fInfo = new FileInfo(filePath);
fInfo.IsReadOnly = readOnly;
}
public bool IsFileReadable(string filePath)
{
try
{
FileAttributes attributes = File.GetAttributes(filePath);
bool isReadable = (attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
return isReadable;
}
catch (Exception ex)
{
Console.WriteLine($"判断文件可读性时出现错误: {ex.Message}");
return false;
}
}
}
}