971 lines
39 KiB
C#
971 lines
39 KiB
C#
using System;
|
||
using System.Collections.Generic;
|
||
using System.ComponentModel;
|
||
using System.Data;
|
||
using System.Drawing;
|
||
using System.Linq;
|
||
using System.Text;
|
||
using System.Windows.Forms;
|
||
using System.IO;
|
||
using Lskj.Core;
|
||
using System.Threading;
|
||
using Microsoft.Win32;
|
||
using System.Collections;
|
||
using System.Text.RegularExpressions;
|
||
using System.Timers;
|
||
|
||
namespace Lskj.TxtFileRead
|
||
{
|
||
public partial class FrmMain : Form
|
||
{
|
||
/// <summary>
|
||
/// ftp地址
|
||
/// </summary>
|
||
private string ftpPath;
|
||
/// <summary>
|
||
/// ftp用户名
|
||
/// </summary>
|
||
private string ftpUsername;
|
||
/// <summary>
|
||
/// ftp密码
|
||
/// </summary>
|
||
private string ftpPassword;
|
||
/// <summary>
|
||
/// ftp类
|
||
/// </summary>
|
||
private FtpHelper ftpHelper;
|
||
/// <summary>
|
||
/// 设定时间
|
||
/// </summary>
|
||
private string setTime;
|
||
/// <summary>
|
||
/// 设定时间集合
|
||
/// </summary>
|
||
private List<string> setTimes = new List<string>();
|
||
/// <summary>
|
||
///复制时间集合
|
||
/// </summary>
|
||
private List<string> ReplicationSetTimes = new List<string>();
|
||
/// <summary>
|
||
/// 下载存放路径
|
||
/// </summary>
|
||
private static string downloadPath = PubUtil.AbsolutelyPath + "ftpFiles\\";
|
||
/// <summary>
|
||
/// 移动存放路径
|
||
/// </summary>
|
||
private static string movePath = PubUtil.AbsolutelyPath + "MoveFiles\\";
|
||
/// <summary>
|
||
/// 数据库名
|
||
/// </summary>
|
||
private string dataBase = string.Empty;
|
||
/// <summary>
|
||
/// 服务器地址
|
||
/// </summary>
|
||
private string serverName = string.Empty;
|
||
/// <summary>
|
||
/// 设置配置信息文件
|
||
/// </summary>
|
||
private string iniFile = "ftpConfig.ini";
|
||
/// <summary>
|
||
/// 配置前缀
|
||
/// </summary>
|
||
private string ftpPrefix = string.Empty;
|
||
/// <summary>
|
||
/// 配置前缀集合
|
||
/// </summary>
|
||
private List<string> ftpPrefixs = new List<string>();
|
||
/// <summary>
|
||
/// 配置前缀和对应sql
|
||
/// </summary>
|
||
private Dictionary<string, string> prefixAndSql = new Dictionary<string, string>();
|
||
/// <summary>
|
||
///每个时间对应每条sqll(默认为每个时间执行所有sql)
|
||
/// </summary>
|
||
private bool SpecialExecution = false;
|
||
|
||
|
||
/// <summary>
|
||
/// 文件名存放位置
|
||
/// </summary>
|
||
private string txtFilePath = PubUtil.AbsolutelyPath + "fileName.txt";
|
||
private DateTime NowDay;//当前日期
|
||
private string fileNames;
|
||
List<string> delfileNames = new List<string>();
|
||
private System.Timers.Timer timer = new System.Timers.Timer();
|
||
private System.Timers.Timer timer1 = new System.Timers.Timer();
|
||
/// <summary>
|
||
/// 当天是否执行判断
|
||
/// </summary>
|
||
private bool isFinish = false;
|
||
|
||
bool flag = false;
|
||
//private static string _regKey = "AA_LS_Erp V2.0";
|
||
|
||
/// <summary>
|
||
/// 是否启动
|
||
/// </summary>
|
||
private bool activate = false;
|
||
|
||
public System.Timers.Timer timer2 = new System.Timers.Timer();
|
||
|
||
public FrmMain()
|
||
{
|
||
InitializeComponent();
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// <para>说明:初始化</para>
|
||
/// <para>创建人:钱雄</para>
|
||
/// <para>创建日期:2020-11-07 </para>
|
||
/// <para>修改人:</para>
|
||
/// <para>修改日期:</para>
|
||
/// <para>修改备注:</para>
|
||
/// <para>版本:1.0</para>
|
||
/// </summary>
|
||
/// <param name="item">The item.</param>
|
||
protected override void OnLoad(EventArgs e)
|
||
{
|
||
//this.timeEdit1.Format = DateTimePickerFormat.Custom;
|
||
//this.timeEdit1.CustomFormat = "HH:mm:ss";
|
||
//IniHelper.Write(iniFile, "time", "07:00:00");
|
||
try
|
||
{
|
||
|
||
setTimes = IniHelper.Read(iniFile, "time").Split(';').ToList();
|
||
ReplicationSetTimes = IniHelper.Read(iniFile, "time").Split(';').ToList();
|
||
SpecialExecution = IniHelper.Read(iniFile, "SpecialExecution").Equals("1");
|
||
|
||
ftpPath = this.txt_ftpAddress.Text = IniHelper.Read(iniFile, "ftpAddress");
|
||
ftpUsername = this.txt_Username.Text = IniHelper.Read(iniFile, "username");
|
||
ftpPassword = this.txtPassword.Text = IniHelper.Read(iniFile, "password");
|
||
dataBase = this.txtDataBase.Text = IniHelper.Read(iniFile, "dataBase");
|
||
serverName = this.txtServerName.Text = IniHelper.Read(iniFile, "serverName");
|
||
fileNames = IniHelper.Read(iniFile, "fileName").ToString();
|
||
ftpPrefix = string.IsNullOrWhiteSpace(IniHelper.Read(iniFile, "ftpPrefix").ToString()) ? "BOSS2ZSCG" : IniHelper.Read(iniFile, "ftpPrefix");//boss2zscg boss3zscg
|
||
|
||
|
||
|
||
//ftpPrefix = "BOSS2GZSCM_DEVNO_REASON_/insert BOSS_REASON_TAB(txtname,txtdate,a,b,c,d,e,f,g)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}');BOSS2GZSCM_DEVNO_TASKSEND_/insert BOSS_TASKSEND_TAB(txtname,txtdate,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}');BOSS2GZCG_FIT_/insert BOSS2ZSCG_FIT(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}');BOSS2GZCG_DEVNO_/insert BOSS2ZSCG_DEVNO(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')";
|
||
//ftpPrefix = "BOSS2GZSCM_DEVNO_RESTASK_/insert BOSS_RESTASK_TAB(txtname,txtdate,a,b,c,d,e,f,g,h)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}');BOSS2GZSCM_DEVNO_REASON_/insert BOSS_REASON_TAB(txtname,txtdate,a,b,c,d,e,f,g)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}');BOSS2GZSCM_DEVNO_TASKSEND_/insert BOSS_TASKSEND_TAB(txtname,txtdate,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}');BOSS2GZSCM_DEVNOREPLACE_/insert BOSS_DEVNOREPLACE_TAB(txtname,txtdate,a,b,c,d,e,f,g)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}');BOSS2GZCG_FIT_/insert BOSS2ZSCG_FIT(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}');BOSS2GZCG_DEVNO_/insert BOSS2ZSCG_DEVNO(txtname,datetime,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q)values('{txtname}','{txtdate}','{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}','{9}','{10}','{11}','{12}','{13}','{14}','{15}','{16}')";
|
||
//IniHelper.Write(iniFile, "ftpPrefix", ftpPrefix);
|
||
|
||
string txtPrefix = string.Empty;
|
||
string tableName = string.Empty;
|
||
foreach (string field in ftpPrefix.Split(';'))
|
||
{
|
||
if (!string.IsNullOrWhiteSpace(field))
|
||
{
|
||
txtPrefix = field.Split('/')[0];
|
||
tableName = field.Split('/')[1];
|
||
ftpPrefixs.Add(txtPrefix);
|
||
prefixAndSql.Add(txtPrefix, tableName);
|
||
}
|
||
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
RefreshLog("文件配置错误\r\n");
|
||
}
|
||
|
||
//ftpPrefix = "BOSS2GZSCM_DEVNO_RESTASK_";
|
||
//start();
|
||
//InsertData(downloadPath + "\\BOSS2GZSCM_DEVNO_RESTASK_20240514.txt");
|
||
//InsertData(downloadPath + "\\BOSS2GZSCM_DEVNO_TASKSEND_20230922.txt");
|
||
|
||
|
||
DBConfig.Instance.DataBase = dataBase;
|
||
DBConfig.Instance.ServerName = serverName;
|
||
|
||
|
||
|
||
if (!File.Exists(txtFilePath))
|
||
{
|
||
FileStream fs = new FileStream(txtFilePath, FileMode.Create, FileAccess.Write);
|
||
//不存在就新建一个文本文件
|
||
StreamWriter sw = new StreamWriter(fs);
|
||
sw.Flush();
|
||
sw.Close();
|
||
fs.Close();
|
||
}
|
||
|
||
//List<string> lines = new List<string>(File.ReadAllLines(txtFilePath).Where(s => !string.IsNullOrEmpty(s)).ToArray());
|
||
////当txt文件内容超过30行,删除第一行内容
|
||
//if (lines.Count > 30)
|
||
// lines.RemoveRange(0, prefixAndSql.Count);//删除当前配置的sql条数
|
||
//File.WriteAllLines(txtFilePath, lines.ToArray());
|
||
//InitTimer();//2023-10-11改成循环,不使用计时器
|
||
|
||
bool RunAutomatically = IniHelper.Read(iniFile, "RunAutomatically").Equals("1");
|
||
if (RunAutomatically)
|
||
{
|
||
this.btnSave.Enabled = false;
|
||
this.timer2.Elapsed += new System.Timers.ElapsedEventHandler(SelfStarting);
|
||
this.timer2.Interval = 2000;
|
||
this.timer2.Enabled = true;
|
||
this.timer2.Start();
|
||
}
|
||
}
|
||
|
||
private void SelfStarting(object sender, ElapsedEventArgs e)
|
||
{
|
||
this.timer2.Enabled = false;
|
||
this.OnSaveClick(null, null);
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// 初始化时间设置
|
||
/// </summary>
|
||
private void InitTimer()
|
||
{
|
||
NowDay = DateTime.Today;
|
||
//设置timer
|
||
timer.Interval = 2000;
|
||
//设置是否重复计时,如果该属性设为False,则只执行timer_Elapsed方法一次。
|
||
timer.AutoReset = true;
|
||
timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);
|
||
|
||
timer1.Interval = 2000;
|
||
timer1.AutoReset = true;
|
||
timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
|
||
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 配置了多个时间,对应时间执行对应sql
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
||
{
|
||
if (NowDay < DateTime.Today)
|
||
{
|
||
NowDay = DateTime.Today;
|
||
isFinish = false;
|
||
}
|
||
|
||
for (int i = 0; i < setTimes.Count; i++)
|
||
{
|
||
string setTime2 = setTimes[i].Substring(0, 5);
|
||
|
||
if (ftpPrefixs.Count >= i + 1)
|
||
{
|
||
ftpPrefix = ftpPrefixs[i];//时间对应的ftpPrefix
|
||
}
|
||
else
|
||
{
|
||
return;
|
||
}
|
||
|
||
|
||
int interception = setTime2.IndexOf('0');
|
||
if (interception == 0)//如果第一个数为0,则删除第一个数,因为DateTime.Now.ToShortTimeString().ToString()不会出现07:00的情况
|
||
{
|
||
setTime2 = setTime2.Substring(1, setTime2.Length - 1);
|
||
}
|
||
|
||
if (setTime2 == DateTime.Now.ToShortTimeString().ToString() && !isFinish)
|
||
{
|
||
isFinish = true;
|
||
start();
|
||
string sqlValue = IniHelper.Read(iniFile, "sqlValue");
|
||
if (!string.IsNullOrEmpty(sqlValue) && DBConfig.Instance.CreateConnection())
|
||
{
|
||
try
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "正在执行sql\r\n");
|
||
OdbcHelper.ExecuteNonQuery(sqlValue);
|
||
RefreshLog(DateTime.Now + ":" + "SQL语句执行成功。\r\n");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "SQL语句执行失败" + ex.Message + "\r\n");
|
||
}
|
||
}
|
||
}
|
||
//timer1.Enabled = true;
|
||
//timer1.Interval = Interval;
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 配置了单个时间,到了时间后执行所有配置sql
|
||
/// </summary>
|
||
/// <param name="sender"></param>
|
||
/// <param name="e"></param>
|
||
private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
|
||
{
|
||
|
||
timer1.Enabled = false;
|
||
start();
|
||
string sqlValue = IniHelper.Read(iniFile, "sqlValue");
|
||
if (!string.IsNullOrEmpty(sqlValue) && DBConfig.Instance.CreateConnection())
|
||
{
|
||
try
|
||
{
|
||
OdbcHelper.ExecuteNonQuery(sqlValue);
|
||
RefreshLog(DateTime.Now + ":" + "SQL语句执行成功。\r\n");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "SQL语句执行失败" + ex.Message + "\r\n");
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
/// <summary>
|
||
/// 到配置时间后执行所有配置sql(新版)
|
||
/// </summary>
|
||
private void Synchronous()
|
||
{
|
||
Thread thread = new Thread(() =>
|
||
{
|
||
while (true)
|
||
{
|
||
try
|
||
{
|
||
if (NowDay < DateTime.Today)
|
||
{
|
||
ReplicationSetTimes = IniHelper.Read(iniFile, "time").Split(';').ToList();
|
||
NowDay = DateTime.Today;
|
||
|
||
}
|
||
int index = 0;
|
||
for (int i = 0; i < ReplicationSetTimes.Count; i++)
|
||
{
|
||
string Time = ReplicationSetTimes[i];// Substring(0, 5);
|
||
if (string.IsNullOrWhiteSpace(Time)) continue;
|
||
|
||
int interception = Time.IndexOf('0');
|
||
if (interception == 0)//如果第一个数为0,则删除第一个数,因为DateTime.Now.ToShortTimeString().ToString()不会出现07:00的情况
|
||
{
|
||
Time = Time.Substring(1, Time.Length - 1);
|
||
}
|
||
DateTime CurrentTime = DateTime.Now;//当前时间
|
||
DateTime dateTime;
|
||
DateTime.TryParse(Time, out dateTime);
|
||
|
||
if (dateTime < CurrentTime)//当前时间大于配置时间就执行
|
||
{
|
||
RefreshLog(DateTime.Now + ":正在连接数据库\r\n");
|
||
if (DBConfig.Instance.CreateConnection())
|
||
{
|
||
RefreshLog(DateTime.Now + ":数据库连接成功\r\n");
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":数据库连接失败\r\n");
|
||
return;
|
||
}
|
||
|
||
//for (int j = 0; j < ftpPrefixs.Count; j++)
|
||
//{
|
||
//}
|
||
|
||
foreach (string item in ftpPrefixs)
|
||
{
|
||
RefreshLog(Time + " : " + item + "\r\n");
|
||
ftpPrefix = item;
|
||
start();
|
||
}
|
||
string sqlValue = IniHelper.Read(iniFile, "sqlValue");
|
||
if (!string.IsNullOrEmpty(sqlValue))
|
||
{
|
||
try
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "正在执行ini配置SQL\r\n");
|
||
OdbcHelper.ExecuteNonQuery(sqlValue);
|
||
RefreshLog(DateTime.Now + ":" + "SQL语句执行成功。\r\n");
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "SQL语句执行失败" + ex.Message + "\r\n");
|
||
}
|
||
}
|
||
RefreshLog(DateTime.Now + ":" + "执行完成\r\n");
|
||
index = i;
|
||
ReplicationSetTimes.RemoveAt(index);//临时时间记录里删除对应记录
|
||
break;
|
||
}
|
||
}
|
||
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "计时器循环错误" + ex.Message + "\r\n");
|
||
}
|
||
finally
|
||
{
|
||
Thread.Sleep(60000);
|
||
}
|
||
}
|
||
});
|
||
thread.IsBackground = true;
|
||
thread.Start();
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// <para>说明:保存ftp地址,下载文件</para>
|
||
/// <para>创建人:钱雄</para>
|
||
/// <para>创建日期:2020-11-04 </para>
|
||
/// <para>修改人:</para>
|
||
/// <para>修改日期:</para>
|
||
/// <para>修改备注:</para>
|
||
/// <para>版本:1.0</para>
|
||
/// </summary>
|
||
/// <param name="item">The item.</param>
|
||
private void OnSaveClick(object sender, EventArgs e)
|
||
{
|
||
ftpPath = this.txt_ftpAddress.Text;
|
||
ftpUsername = this.txt_Username.Text;
|
||
ftpPassword = this.txtPassword.Text;
|
||
//setTime = setTimes.Length > 1 ? this.timeEdit1.Text + ";" + this.timeEdit2 : this.timeEdit1.Text;
|
||
dataBase = this.txtDataBase.Text;
|
||
serverName = this.txtServerName.Text;
|
||
//Interval = Convert.ToInt32(this.txtInterval.Text) * 60 * 1000;
|
||
|
||
if (string.IsNullOrEmpty(ftpPath))
|
||
{
|
||
MessageBox.Show("ftp地址不能为空!");
|
||
this.txt_ftpAddress.Focus();
|
||
}
|
||
if (string.IsNullOrEmpty(ftpUsername))
|
||
{
|
||
MessageBox.Show("用户名不能为空!");
|
||
this.txt_Username.Focus();
|
||
}
|
||
if (string.IsNullOrEmpty(ftpPassword))
|
||
{
|
||
MessageBox.Show("密码不能为空!");
|
||
this.txtPassword.Focus();
|
||
}
|
||
if (string.IsNullOrEmpty(dataBase))
|
||
{
|
||
MessageBox.Show("数据库不能为空!");
|
||
this.txtDataBase.Focus();
|
||
}
|
||
if (string.IsNullOrEmpty(serverName))
|
||
{
|
||
MessageBox.Show("服务器地址不能为空!");
|
||
this.txtServerName.Focus();
|
||
}
|
||
if (!string.IsNullOrEmpty(ftpPath) && !string.IsNullOrEmpty(ftpUsername) && !string.IsNullOrEmpty(ftpPassword) && !string.IsNullOrEmpty(dataBase) && !string.IsNullOrEmpty(serverName))
|
||
{
|
||
//IniHelper.Write(iniFile, "time", setTime);
|
||
IniHelper.Write(iniFile, "ftpAddress", ftpPath);
|
||
IniHelper.Write(iniFile, "username", ftpUsername);
|
||
IniHelper.Write(iniFile, "password", ftpPassword);
|
||
IniHelper.Write(iniFile, "serverName", serverName);
|
||
IniHelper.Write(iniFile, "dataBase", dataBase);
|
||
|
||
//设置数据库名和服务器地址
|
||
//RegistryKey regKey = Registry.CurrentUser;
|
||
//RegistryKey subKey = regKey.OpenSubKey(_regKey);
|
||
//subKey = subKey.OpenSubKey("File", true);
|
||
//subKey.SetValue("datastr", dataBase);
|
||
//subKey.SetValue("ServerName", serverName);
|
||
DBConfig.Instance.DataBase = dataBase;
|
||
DBConfig.Instance.ServerName = serverName;
|
||
|
||
show_txt.Text = "";
|
||
RefreshLog(DateTime.Now + ":开始启动\r\n");
|
||
if (DBConfig.Instance.CreateConnection())
|
||
{
|
||
if (!activate)
|
||
{
|
||
activate = true;
|
||
RefreshLog(DateTime.Now + ":启动中,请稍后\r\n");
|
||
Synchronous();
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":已经启动\r\n");
|
||
}
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":数据库连接失败\r\n");
|
||
}
|
||
|
||
|
||
|
||
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// 显示信息设置
|
||
/// </summary>
|
||
/// <param name="msg"></param>
|
||
public void RefreshLog(string msg)
|
||
{
|
||
Invoke((EventHandler)delegate
|
||
{
|
||
show_txt.Text += msg;
|
||
show_txt.ScrollToCaret();
|
||
});
|
||
}
|
||
|
||
/// <summary>
|
||
/// <para>说明:下载文件插入到数据库</para>
|
||
/// <para>创建人:钱雄</para>
|
||
/// <para>创建日期:2020-11-04 </para>
|
||
/// <para>修改人:</para>
|
||
/// <para>修改日期:</para>
|
||
/// <para>修改备注:</para>
|
||
/// <para>版本:1.0</para>
|
||
/// </summary>
|
||
/// <param name="item">The item.</param>
|
||
public void start()
|
||
{
|
||
delfileNames.Clear();
|
||
flag = false;
|
||
try
|
||
{
|
||
ftpHelper = new FtpHelper(ftpPath, "", ftpUsername, ftpPassword);
|
||
|
||
//测试时不下载
|
||
//if (false)
|
||
//{
|
||
|
||
|
||
List<string> lists = ftpHelper.GetAllList();
|
||
if (lists.Count == 0)
|
||
{
|
||
RefreshLog(DateTime.Now + ":ftp上没有文件需要下载\r\n");
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":获取到" + lists.Count + "个文件\r\n");
|
||
}
|
||
|
||
|
||
for (int i = 0; i < lists.Count; i++)
|
||
{
|
||
|
||
if (lists[i].Contains(ftpPrefix))
|
||
{
|
||
//文件下载
|
||
if (!Directory.Exists(@downloadPath))
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + @downloadPath + "文件夹不存在,正在创建\r\n");
|
||
Directory.CreateDirectory(@downloadPath);//不存在就创建目录
|
||
}
|
||
if (File.Exists(@downloadPath + lists[i]))
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + lists[i] + "文件已存在\r\n");
|
||
//list.Add(lists[i]);
|
||
delfileNames.Add(lists[i]);
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + lists[i] + "文件下载中\r\n");
|
||
if (ftpHelper.FtpDownload(lists[i].ToString(), @downloadPath + lists[i], true))
|
||
RefreshLog(DateTime.Now + ":" + lists[i].Substring(lists[i].LastIndexOf('\\') + 1) + "文件成功下载到" + downloadPath + "\r\n");
|
||
delfileNames.Add(lists[i]);
|
||
|
||
|
||
}
|
||
}
|
||
}
|
||
|
||
|
||
// }
|
||
|
||
if (!FileUtilHelper.IsEmptyDirectory(downloadPath))
|
||
{
|
||
string[] filesPath = ftpHelper.GetFiles(new DirectoryInfo(downloadPath), "*.txt");
|
||
int importCount = 0;
|
||
for (int b = 0; b < filesPath.Length; b++)
|
||
{
|
||
string filename;
|
||
string[] txtValue = File.ReadAllLines(txtFilePath).Where(s => !string.IsNullOrEmpty(s)).ToArray();
|
||
//判断txt文件中保存的文件名是否已经导入过,没有导入的则导入进去
|
||
bool exists = ((IList)txtValue).Contains(filesPath[b].Substring(filesPath[b].LastIndexOf('\\') + 1).Trim());
|
||
if (exists)
|
||
{
|
||
continue;
|
||
}
|
||
else
|
||
{
|
||
filename = filesPath[b].Substring(filesPath[b].LastIndexOf('\\') + 1);
|
||
if (filename.Contains(ftpPrefix))
|
||
{
|
||
InsertData(downloadPath + filename);
|
||
importCount++;
|
||
flag = true;
|
||
}
|
||
}
|
||
}
|
||
if (importCount == 0)
|
||
{
|
||
RefreshLog(DateTime.Now + ":没有要导入的数据\r\n");
|
||
}
|
||
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":没有要导入的数据\r\n");
|
||
}
|
||
|
||
|
||
}
|
||
catch (Exception e)
|
||
{
|
||
MessageBox.Show("下载文件出错:" + e.Message);
|
||
}
|
||
}
|
||
|
||
/// <summary>
|
||
/// <para>说明:向数据库插入数据</para>
|
||
/// <para>创建人:钱雄</para>
|
||
/// <para>创建日期:2020-11-10 </para>
|
||
/// <para>修改人:</para>
|
||
/// <para>修改日期:</para>
|
||
/// <para>修改备注:</para>
|
||
/// <para>版本:1.0</para>
|
||
/// </summary>
|
||
public void InsertData(string path)
|
||
{
|
||
Encoding FileCoding = GetFileEncodeType(path);//获取文件编码格式
|
||
string[] files = File.ReadAllLines(path.TrimEnd('\r'), FileCoding);//Encoding.Default
|
||
string fileName = path.Substring(path.LastIndexOf('\\') + 1).TrimEnd('\r').TrimEnd('\n').Trim();
|
||
RefreshLog(DateTime.Now + ":" + fileName + "文件读取中\r\n");
|
||
int wrongNumber = 1;//错误编号 1为拼接sql时错误,2为执行sql时错误
|
||
string errorContent = string.Empty;
|
||
try
|
||
{
|
||
string sqlValue = string.Empty;
|
||
string sqlValueAll = string.Empty;
|
||
//string data = string.Empty;
|
||
if (!prefixAndSql.ContainsKey(ftpPrefix))
|
||
{
|
||
RefreshLog("文件配置错误,文件名不匹配。\r\n");
|
||
return;
|
||
}
|
||
string sql = prefixAndSql[ftpPrefix];
|
||
sql = sql.Replace("{txtname}", fileName).Replace("{txtdate}", DateTime.Now.ToString());
|
||
if (files.Length > 0)
|
||
{
|
||
//string[] columnsData = new string[files[0].Split('~').Length];
|
||
int count = Regex.Matches(sql, @"\{[^\}]*\}").Count;
|
||
RefreshLog(DateTime.Now + ":开始拼接sql" + path + "\r\n");
|
||
for (int i = 0; i < files.Length; i++)
|
||
{
|
||
errorContent = files[i];
|
||
//string takleSql = "select ";
|
||
//for (int j = 0; j < files[i].Split('~').Length; j++)
|
||
//{
|
||
// //data = files[i].Split('~')[j];
|
||
// columnsData[j] = files[i].Split('~')[j];
|
||
// takleSql = takleSql + "'" + columnsData[j].Replace("'", "''") + "' as '" + j + "',";
|
||
//}
|
||
//takleSql = takleSql.Trim(',');
|
||
//DataTable table = OdbcHelper.ExecuteDataTable(takleSql);
|
||
//sqlValue = ReplaceRowParam(table.Rows[0], sql);
|
||
|
||
sqlValue = sql;
|
||
|
||
|
||
for (int j = 0; j <= count-1; j++)
|
||
{
|
||
|
||
//columnsData[j] = files[i].Split('~')[j];
|
||
string text = "";
|
||
if (files[i].Split('~').Length >= j+1)
|
||
{
|
||
text = files[i].Split('~')[j];
|
||
}
|
||
string key = "{" + j + "}";
|
||
sqlValue = sqlValue.Replace(key, text);
|
||
|
||
}
|
||
|
||
|
||
|
||
|
||
sqlValueAll += sqlValue + ";";
|
||
}
|
||
//254517
|
||
RefreshLog(DateTime.Now + ":" + fileName + "数据插入中\r\n");
|
||
wrongNumber = 2;
|
||
if (string.IsNullOrEmpty(sqlValueAll))
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "没有要插入的数据\r\n");
|
||
}
|
||
else
|
||
{
|
||
int counts = 0;
|
||
|
||
counts = OdbcHelper.ExecuteNonQuery(sqlValueAll);
|
||
if (counts > 0)
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "插入完成" + counts + "条\r\n");
|
||
RefreshLog(DateTime.Now + ":" + "正在移动\r\n");
|
||
//fileNames = path.Substring(path.LastIndexOf('\\') + 1).TrimEnd('\r').TrimEnd('\n').Trim();
|
||
StreamWriter sw = new StreamWriter(@txtFilePath, true);//true表示追加
|
||
sw.WriteLine(fileName);
|
||
sw.Flush();
|
||
sw.Close();
|
||
|
||
if (ftpHelper.fileDelete(fileName))
|
||
{
|
||
RefreshLog(DateTime.Now + ":ftp文件" + fileName + "删除成功\r\n");
|
||
}
|
||
|
||
if (!Directory.Exists(@movePath))
|
||
{
|
||
Directory.CreateDirectory(@movePath);//不存在就创建目录
|
||
}
|
||
else
|
||
{
|
||
if (FileUtilHelper.Move(path.Trim(), @movePath))
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "移动成功\r\n");
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
MessageBox.Show("插入失败");
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + fileName + "没有数据\r\n");
|
||
//记录已经完成的文件
|
||
StreamWriter sw = new StreamWriter(@txtFilePath, true);//true表示追加
|
||
sw.WriteLine(fileName);
|
||
sw.Flush();
|
||
sw.Close();
|
||
if (ftpHelper.fileDelete(fileName))
|
||
{
|
||
RefreshLog(DateTime.Now + ":ftp文件" + fileName + "删除成功\r\n");
|
||
}
|
||
|
||
if (!Directory.Exists(@movePath))
|
||
{
|
||
Directory.CreateDirectory(@movePath);//不存在就创建目录
|
||
}
|
||
else
|
||
{
|
||
if (FileUtilHelper.Move(path.Trim(), @movePath))
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + "移动成功\r\n");
|
||
}
|
||
}
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
|
||
if (wrongNumber == 1)
|
||
{
|
||
MessageBox.Show(DateTime.Now + ": 拼接Sql数据出错 :" + ex.Message);
|
||
writeLogException(ex, path + " : sql拼接错误 : " + errorContent);
|
||
}
|
||
else
|
||
{
|
||
MessageBox.Show(DateTime.Now + ": 向数据库插入数据出错 :" + ex.Message);
|
||
writeLogException(ex, path + " : " + "拼接sql执行错误");
|
||
}
|
||
}
|
||
}
|
||
|
||
//报错时写入日志操作
|
||
public static void writeLogException(Exception ex, string errorContent) //异常信息写入日志
|
||
{
|
||
//获取异常信息的类、行号、异常 信息
|
||
string exceptionStr = ex.StackTrace.ToString().Substring(ex.StackTrace.ToString().LastIndexOf('\\') + 1)
|
||
+ " " + ex.Message + " 报错内容:" + errorContent;
|
||
exceptionStr = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + " " + exceptionStr;
|
||
//自己定义一个存储日志文件的位置
|
||
string sFilePath = PubUtil.AbsolutelyPath + "日志";
|
||
string sFileName = DateTime.Now.ToString("yyyy-MM-dd") + ".log";
|
||
sFileName = sFilePath + @"\\" + sFileName; //文件
|
||
if (!Directory.Exists(sFilePath))
|
||
{
|
||
Directory.CreateDirectory(sFilePath);
|
||
}
|
||
FileStream fs;
|
||
StreamWriter sw;
|
||
if (System.IO.File.Exists(sFileName))
|
||
{
|
||
fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
|
||
}
|
||
else
|
||
{
|
||
fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
|
||
}
|
||
sw = new StreamWriter(fs);
|
||
sw.WriteLine(exceptionStr);
|
||
sw.Close();
|
||
fs.Close();
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// 判断文件格式(ANSI和utf-8)
|
||
/// </summary>
|
||
/// <param name="filename"></param>
|
||
/// <returns></returns>
|
||
public System.Text.Encoding GetFileEncodeType(string filename)
|
||
{
|
||
try
|
||
{
|
||
filename = filename.Replace("\r", "");
|
||
using (FileStream fs = new FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
|
||
{
|
||
byte[] Unicode = new byte[] { 0xFF, 0xFE, 0x41 };
|
||
byte[] UnicodeBIG = new byte[] { 0xFE, 0xFF, 0x00 };
|
||
byte[] UTF8 = new byte[] { 0xEF, 0xBB, 0xBF };//带BOM
|
||
Encoding reVal = Encoding.Default;
|
||
BinaryReader br = new BinaryReader(fs);
|
||
int length;
|
||
int.TryParse(fs.Length.ToString(), out length);
|
||
byte[] ss = br.ReadBytes(length);
|
||
if (IsUTF8Bytes(ss) ||
|
||
(ss[0] == UTF8[0] && ss[1] == UTF8[1] && ss[2] == UTF8[2]))
|
||
reVal = Encoding.UTF8;
|
||
else if (ss[0] == UnicodeBIG[0] && ss[1] == UnicodeBIG[1] && ss[2] == UnicodeBIG[2])
|
||
reVal = Encoding.BigEndianUnicode;
|
||
else if (ss[0] == Unicode[0] && ss[1] == Unicode[1] && ss[2] == Unicode[2])
|
||
reVal = Encoding.Unicode;
|
||
br.Close();
|
||
|
||
return reVal;
|
||
}
|
||
}
|
||
catch (Exception ex)
|
||
{
|
||
RefreshLog(DateTime.Now + ":" + filename + "获取编码格式失败,使用电脑默认编码格式\r\n");
|
||
return Encoding.Default;
|
||
}
|
||
|
||
}
|
||
/// <summary>
|
||
/// 判断是否是不带 BOM 的 UTF8 格式
|
||
/// </summary>
|
||
/// <param name=“data“></param>
|
||
/// <returns></returns>
|
||
private static bool IsUTF8Bytes(byte[] data)
|
||
{
|
||
int charByteCounter = 1;//计算当前正分析的字符应还有的字节数
|
||
byte curByte;//当前分析的字节
|
||
for (int i = 0; i < data.Length; i++)
|
||
{
|
||
curByte = data[i];
|
||
if (charByteCounter == 1)
|
||
{
|
||
if (curByte >= 0x80)
|
||
{
|
||
//判断当前
|
||
while (((curByte <<= 1) & 0x80) != 0)
|
||
{
|
||
charByteCounter++;
|
||
}
|
||
//标记位首位若为非0 则至少以2个1开始,如:110XXXXX.....1111110X
|
||
if (charByteCounter == 1 || charByteCounter > 6)
|
||
{
|
||
return false;
|
||
}
|
||
}
|
||
}
|
||
else
|
||
{
|
||
//若是UTF-8 此时第一位必须为1
|
||
if ((curByte & 0xC0) != 0x80)
|
||
{
|
||
return false;
|
||
}
|
||
charByteCounter--;
|
||
}
|
||
}
|
||
if (charByteCounter > 1)
|
||
{
|
||
throw new Exception("非预期的byte格式");
|
||
}
|
||
return true;
|
||
}
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
/// <summary>
|
||
/// <para>说明:说明:替换"{字段}"格式字符串,已替换操作员等信息</para>
|
||
/// <para>创建人:龚宇超</para>
|
||
/// <para>创建日期:2017-10-30 </para>
|
||
/// <para>修改人:</para>
|
||
/// <para>修改日期:</para>
|
||
/// <para>修改备注:</para>
|
||
/// <para>版本:1.0</para>
|
||
/// </summary>
|
||
/// <param name="row">The row.</param>
|
||
/// <param name="param">The parameter.</param>
|
||
/// <returns>System.String.</returns>
|
||
public static string ReplaceRowParam(DataRow row, string param)
|
||
{
|
||
|
||
if (row == null) return param;
|
||
List<string> condition = GetParamFields(param);
|
||
foreach (string item in condition)
|
||
{
|
||
string field = item.Replace("{", "").Replace("}", "");
|
||
string value = row.Table.Columns.Contains(field) ? row[field] + "" : item;
|
||
value = value.Replace("'", "''");
|
||
param = param.Replace(item, value);
|
||
}
|
||
return param;
|
||
}
|
||
|
||
/// <summary>
|
||
/// <para>说明:获取sql语句中替换</para>
|
||
/// <para>创建人:龚宇超</para>
|
||
/// <para>创建日期:2017-09-04 </para>
|
||
/// <para>修改人:</para>
|
||
/// <para>修改日期:</para>
|
||
/// <para>修改备注:</para>
|
||
/// <para>版本:1.0</para>
|
||
/// </summary>
|
||
/// <returns>List<System.String>.</returns>
|
||
public static List<string> GetParamFields(string defaultValue)
|
||
{
|
||
List<string> list = new List<string>();
|
||
Regex regex = new Regex("{([^{])+}");
|
||
MatchCollection mcs = regex.Matches(defaultValue);
|
||
foreach (Match item in mcs)
|
||
{
|
||
if (list.IndexOf(item.Value) == -1)
|
||
list.Add(item.Value);
|
||
}
|
||
return list;
|
||
}
|
||
}
|
||
}
|