Main.cs 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499
  1. using Microsoft.Office.Interop.Excel;
  2. using System;
  3. using System.Collections.Concurrent;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Data;
  7. using System.Drawing;
  8. using System.Globalization;
  9. using System.IO;
  10. using System.IO.Compression;
  11. using System.Linq;
  12. using System.Media;
  13. using System.Net;
  14. using System.Runtime.InteropServices;
  15. using System.Security.Principal;
  16. using System.Text;
  17. using System.Text.RegularExpressions;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. using UAS_Tools_HY;
  22. using UAS_Tools_HY.Properties;
  23. using UAS_Tools_HY.PublicMethods;
  24. using Action = System.Action;
  25. using Application = Microsoft.Office.Interop.Excel.Application;
  26. using DataTable = System.Data.DataTable;
  27. using Timer = System.Windows.Forms.Timer;
  28. namespace UAS_MES_Tools
  29. {
  30. public partial class Main : Form
  31. {
  32. string _Account, _Password, _UserName;
  33. DataTable dt;
  34. Timer loadTime;
  35. string minTime, maxTime;
  36. string curRuleId, curRule, curRuleLeng;
  37. int ishaveInd;
  38. Timer File_timer;
  39. Timer File_timer1;
  40. string saveFiles;
  41. int currentNum = 1;
  42. private CancellationTokenSource _currentOperationCts;
  43. public Main(string account, string password)
  44. {
  45. _Account = account;
  46. _Password = password;
  47. InitializeComponent();
  48. }
  49. private void Main_Load(object sender, EventArgs e)
  50. {
  51. currUser.Text = "当前账户: " + _Account;
  52. dt = ConnectDB.ExecuteSelect($"select * from employee where em_code = '{_Account}'");
  53. if (dt.Rows.Count > 0)
  54. {
  55. _UserName = dt.Rows[0]["em_name"].ToString();
  56. }
  57. loadTime_Tick(null, null);
  58. loadTime = new Timer();
  59. loadTime.Interval = 1000;
  60. loadTime.Tick += loadTime_Tick;
  61. loadTime.Start();
  62. SN.SelectAll();
  63. SN.Focus();
  64. settingLeftInput1.Text = BaseUtil.GetCacheData("SettingCount").ToString();
  65. settingLeftInput2.Text = BaseUtil.GetCacheData("SettingVolume").ToString();
  66. if (string.IsNullOrEmpty(BaseUtil.GetCacheData("SettingVolume").ToString())) dSum.Text = "0";
  67. else dSum.Text = BaseUtil.GetCacheData("SettingVolume").ToString();
  68. settingRightInput1.Text = BaseUtil.GetCacheData("SettingNGPath").ToString();
  69. settingRightInput2.Text = BaseUtil.GetCacheData("SettingExportPath").ToString();
  70. QDcheckbox1.Checked = true;
  71. QDdtp2.Value = QDdtp1.Value.AddDays(1);
  72. rulesQuery_Click(null, null);
  73. QDquery_Click(null, null);
  74. saveFiles = Path.Combine(Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).FullName, $"FtpFiles");
  75. if (!Directory.Exists(saveFiles))
  76. {
  77. Directory.CreateDirectory(saveFiles);
  78. }
  79. //saveFiles = Path.Combine(saveFiles, DateTime.Now.ToString("yyyyMMdd"));
  80. //if (!Directory.Exists(saveFiles))
  81. //{
  82. // Directory.CreateDirectory(saveFiles);
  83. //}
  84. File_timer = new Timer();
  85. File_timer.Interval = 30 * 1000;
  86. File_timer.Tick += Timer_Tick;
  87. timerVal.Text = "30";
  88. FileCountVal.Text = "10";
  89. FtpPathVal.Text = "ftp://10.18.13.48:21";
  90. handExeVal.Text = "120";
  91. File_timer1 = new Timer();
  92. File_timer1.Interval = Convert.ToInt32(handExeVal.Text) * 1000;
  93. File_timer1.Tick += FileTimer_Tick;
  94. }
  95. private void SN_KeyDown(object sender, KeyEventArgs e)
  96. {
  97. if (e.KeyCode != Keys.Enter) return;
  98. if(checkPagination.SelectedIndex != 0) checkPagination.SelectedIndex = 0;
  99. if (CheckEnter()) return;
  100. bool checkRes = true;
  101. if (radio1.Checked)
  102. {
  103. dt = ConnectDB.ExecuteSelect($@"SELECT COUNT(1) sum FROM dcrlogexcel WHERE item = '{SN.Text.Trim()}'");
  104. if (dt.Rows[0]["sum"].ToString() == "0")
  105. {
  106. PlaySound("NG");
  107. MessageBox.Show($"{SN.Text.Trim()},没有DCR测试数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  108. checkRes = false;
  109. return;
  110. }
  111. }
  112. if (FormMethods.IsCheckSNRules(curRule, SN.Text.Trim(), curRuleLeng))
  113. {
  114. PlaySound("NG");
  115. MessageBox.Show($"{SN.Text.Trim()},不符合条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  116. checkRes = false;
  117. return;
  118. }
  119. dt = ConnectDB.ExecuteSelect($@"select * from g_packing_sncheck where sn = '{SN.Text.Trim()}'");
  120. if (dt.Rows.Count > 0)
  121. {
  122. PlaySound("NG");
  123. MessageBox.Show($"{SN.Text.Trim()},历史记录中已核对", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  124. checkRes = false;
  125. return;
  126. }
  127. ishaveInd = -1;
  128. if (Datas.Rows.Count > 0)
  129. {
  130. foreach (DataGridViewRow item in Datas.Rows)
  131. {
  132. if (SN.Text.Trim() == item.Cells[0].Value.ToString())
  133. {
  134. ishaveInd = Datas.Rows.IndexOf(item);
  135. }
  136. }
  137. }
  138. if (ishaveInd >= 0)
  139. {
  140. PlaySound("NG");
  141. MessageBox.Show($"{SN.Text.Trim()},已核对装箱", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  142. checkRes = false;
  143. return;
  144. /*int iCou = Convert.ToInt32(Datas.Rows[ishaveInd].Cells[2].Value);
  145. iCou += 1;
  146. Datas.Rows[ishaveInd].Cells[3].Value = currTime.Text;
  147. Datas.Rows[ishaveInd].Cells[6].Value = checkRes ? "OK" : "NG";
  148. PlaySound("OK");*/
  149. }
  150. else
  151. {
  152. DataGridViewRow row = new DataGridViewRow();
  153. row.CreateCells(Datas);
  154. row.Cells[0].Value = SN.Text.Trim();
  155. row.Cells[1].Value = BoxNo.Text.Trim();
  156. row.Cells[2].Value = 1;
  157. row.Cells[3].Value = currTime.Text;
  158. row.Cells[4].Value = _UserName;
  159. row.Cells[5].Value = radio1.Checked ? "是" : "否";
  160. row.Cells[6].Value = checkRes ? "OK" : "NG";
  161. Datas.Rows.Add(row);
  162. PlaySound("OK");
  163. Datas.FirstDisplayedScrollingRowIndex = Datas.Rows.Count - 1;
  164. try
  165. {
  166. int typeNum = ChangeDetail(row);
  167. if (typeNum == 1)
  168. {
  169. SN.Focus();
  170. SN.SelectAll();
  171. SN.Text = "";
  172. }
  173. else if (typeNum == 2)
  174. {
  175. SN.Text = "";
  176. dCount.Text = "0";
  177. BoxNo.Enabled = true;
  178. BoxNo.Focus();
  179. BoxNo.SelectAll();
  180. //BoxNo.Text = "";
  181. //Datas.Rows.Clear();
  182. }
  183. QDquery_Click(null, null);
  184. if (Datas.Rows.Count == Convert.ToInt32(settingLeftInput1.Text))
  185. {
  186. Datas.Rows.Clear();
  187. }
  188. }
  189. catch (Exception ex)
  190. {
  191. MessageBox.Show(ex.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  192. return;
  193. }
  194. }
  195. }
  196. private int ChangeDetail(DataGridViewRow row)
  197. {
  198. int inputSum = Convert.ToInt32(dCount.Text);
  199. dCount.Text = (inputSum + 1).ToString();
  200. int insertCount = ConnectDB.ExecuteInsert($@"INSERT INTO g_packing_sncheck (work_order,part_no,sn,outbox_no,
  201. count,update_time,update_name,check_id,rule_name,rule_value,capacity,ISCHECHK_DCR,rule_id)
  202. VALUES ( '', '', '{row.Cells[0].Value}', '{row.Cells[1].Value}',
  203. '{row.Cells[2].Value}',sysdate,'{_UserName}',packcheckid_seq.NEXTVAL,'{dRules.Text.Trim()}','{curRule}','{dSum.Text}','{row.Cells[5].Value}','{curRuleId}' )");
  204. if (Convert.ToInt32(dCount.Text) < Convert.ToInt32(dSum.Text))
  205. {
  206. return 1;
  207. }
  208. else
  209. {
  210. return 2;
  211. }
  212. //if(Convert.ToInt32(dCount.Text) == Convert.ToInt32(dSum.Text))
  213. //{
  214. // foreach (DataGridViewRow item in Datas.Rows)
  215. // {
  216. // int insertCount = ConnectDB.ExecuteInsert($@"INSERT INTO g_packing_sncheck (work_order,part_no,sn,outbox_no,
  217. // count,update_time,update_name,check_id,rule_name,rule_value)
  218. // VALUES ( '', '', '{item.Cells[0].Value}', '{item.Cells[1].Value}',
  219. // '{item.Cells[2].Value}',sysdate,'{_UserName}',packcheckid_seq.NEXTVAL,'{dRules.Text.Trim()}','{curRule}' )");
  220. // }
  221. // return true;
  222. //}
  223. //else
  224. //{
  225. // return false;
  226. //}
  227. }
  228. private void BoxNo_Leave(object sender, EventArgs e)
  229. {
  230. if (!string.IsNullOrEmpty(BoxNo.Text))
  231. {
  232. KeyEventArgs KeyEventArg = new KeyEventArgs(Keys.Enter);
  233. BoxNo_KeyDown(null, KeyEventArg);
  234. }
  235. }
  236. private void BoxNo_KeyDown(object sender, KeyEventArgs e)
  237. {
  238. if (e.KeyCode != Keys.Enter) return;
  239. dt = ConnectDB.ExecuteSelect($@"SELECT * FROM g_packing_sncheck a,g_packing_rules b WHERE a.outbox_no = '{BoxNo.Text}' AND a.rule_id = b.rule_id");
  240. if (dt.Rows.Count > 0)
  241. {
  242. if (Convert.ToInt32(dt.Rows[0]["CAPACITY"].ToString()) > dt.Rows.Count)
  243. {
  244. dRules.Text = dt.Rows[0]["RULE_NAME"].ToString();
  245. curRule = dt.Rows[0]["RULE_VALUE"].ToString();
  246. curRuleId = dt.Rows[0]["RULE_ID"].ToString();
  247. curRuleLeng = dt.Rows[0]["RULE_LENGTH"].ToString();
  248. dRules.Enabled = false;
  249. radio1.Checked = dt.Rows[0]["ISCHECHK_DCR"].ToString() == "是" ? true : false;
  250. dCount.Text = dt.Rows.Count.ToString();
  251. settingLeftInput2.Text = dt.Rows[0]["CAPACITY"].ToString();
  252. dSum.Text = dt.Rows[0]["CAPACITY"].ToString();
  253. BaseUtil.SetCacheData("SettingVolume", dt.Rows[0]["CAPACITY"].ToString());
  254. Datas.Rows.Clear();
  255. foreach (DataRow item in dt.Rows)
  256. {
  257. DataGridViewRow row = new DataGridViewRow();
  258. row.CreateCells(Datas);
  259. row.Cells[0].Value = item["SN"].ToString();
  260. row.Cells[1].Value = item["OUTBOX_NO"].ToString();
  261. row.Cells[2].Value = item["COUNT"].ToString();
  262. row.Cells[3].Value = item["UPDATE_TIME"].ToString();
  263. row.Cells[4].Value = item["UPDATE_NAME"].ToString();
  264. row.Cells[5].Value = item["ISCHECHK_DCR"].ToString();
  265. row.Cells[6].Value = "OK";
  266. Datas.Rows.Add(row);
  267. }
  268. }
  269. else
  270. {
  271. BoxNo.Focus();
  272. BoxNo.SelectAll();
  273. MessageBox.Show($"核对完成,此箱{BoxNo.Text} 已装满{dt.Rows[0]["CAPACITY"].ToString()} 个,请扫描未核对箱号", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  274. BoxNo.Text = "";
  275. return;
  276. }
  277. }
  278. if (CheckEnter())
  279. {
  280. BoxNo.Text = "";
  281. return;
  282. }
  283. /*if (Datas.Rows.Count > 0)
  284. {
  285. foreach(DataGridViewRow item in Datas.Rows)
  286. {
  287. item.Cells[1].Value = BoxNo.Text.Trim();
  288. }
  289. }*/
  290. BoxNo.Enabled = false;
  291. SN.SelectAll();
  292. SN.Focus();
  293. }
  294. private bool CheckEnter()
  295. {
  296. if (string.IsNullOrEmpty(settingLeftInput1.Text))
  297. {
  298. MessageBox.Show("请维护列表记录数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  299. return true;
  300. }
  301. if (string.IsNullOrEmpty(settingLeftInput2.Text))
  302. {
  303. MessageBox.Show("请维护箱内容量", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  304. return true;
  305. }
  306. if (!Regex.IsMatch(dSum.Text, @"^[1-9]\d*$"))
  307. {
  308. MessageBox.Show("箱内容量维护应为正整数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  309. return true;
  310. }
  311. if (string.IsNullOrEmpty(dRules.Text))
  312. {
  313. MessageBox.Show("请选择条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  314. return true;
  315. }
  316. if (dRules.Enabled)
  317. {
  318. MessageBox.Show("请选择确认条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  319. return true;
  320. }
  321. return false;
  322. }
  323. private void settingLeftSubmit_Click(object sender, EventArgs e)
  324. {
  325. if (string.IsNullOrEmpty(settingLeftInput1.Text))
  326. {
  327. MessageBox.Show("请输入列表记录数", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  328. return;
  329. }
  330. if (string.IsNullOrEmpty(settingLeftInput2.Text))
  331. {
  332. MessageBox.Show("请输入箱内容量", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  333. return;
  334. }
  335. if (Convert.ToInt32(dCount.Text) > 0)
  336. {
  337. if(Convert.ToInt32(dSum.Text) > Convert.ToInt32(settingLeftInput2.Text))
  338. {
  339. MessageBox.Show($"已扫描{Convert.ToInt32(dCount.Text)} 个产品,修改箱容量需大于{Convert.ToInt32(settingLeftInput2.Text)} ", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  340. return;
  341. }
  342. }
  343. BaseUtil.SetCacheData("SettingCount", settingLeftInput1.Text);
  344. BaseUtil.SetCacheData("SettingVolume", settingLeftInput2.Text);
  345. dSum.Text = BaseUtil.GetCacheData("SettingVolume").ToString();
  346. MessageBox.Show("已提交扫描设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  347. }
  348. private void settingRightSubmit_Click(object sender, EventArgs e)
  349. {
  350. if (string.IsNullOrEmpty(settingRightInput2.Text))
  351. {
  352. MessageBox.Show("请选择导出文件目录", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  353. return;
  354. }
  355. if(!string.IsNullOrEmpty(settingRightInput1.Text)) BaseUtil.SetCacheData("SettingNGPath", settingRightInput1.Text);
  356. BaseUtil.SetCacheData("SettingExportPath", settingRightInput2.Text);
  357. MessageBox.Show("已提交文件设置", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  358. }
  359. private void QDquery_Click(object sender, EventArgs e)
  360. {
  361. StringBuilder filterStr = new StringBuilder();
  362. if (!string.IsNullOrEmpty(QDInput1.Text))
  363. {
  364. filterStr.Append($"WHERE instr(SN,'{QDInput1.Text}') > 0");
  365. }
  366. if (!string.IsNullOrEmpty(QDInput2.Text))
  367. {
  368. if (filterStr.Length == 0)
  369. {
  370. filterStr.Append($"WHERE instr(OUTBOX_NO,'{QDInput2.Text}') > 0");
  371. }
  372. else
  373. {
  374. filterStr.Append($" and instr(OUTBOX_NO, '{QDInput2.Text}') > 0");
  375. }
  376. }
  377. if (QDcheckbox1.Checked)
  378. {
  379. string dtp1 = QDdtp1.Value.ToString("yyyy-MM-dd 00:00:00");
  380. string dtp2 = QDdtp2.Value.ToString("yyyy-MM-dd 00:00:00");
  381. if (filterStr.Length == 0)
  382. {
  383. filterStr.Append($"WHERE update_time > TO_DATE('{dtp1}','YYYY-MM-DD HH24:MI:SS') AND update_time <= TO_DATE('{dtp2}','YYYY-MM-DD HH24:MI:SS')");
  384. }
  385. else
  386. {
  387. filterStr.Append($" AND update_time > TO_DATE('{dtp1}','YYYY-MM-DD HH24:MI:SS') AND update_time <= TO_DATE('{dtp2}','YYYY-MM-DD HH24:MI:SS')");
  388. }
  389. }
  390. if(sender == null)
  391. {
  392. Task.Run(() =>
  393. {
  394. dt = ConnectDB.ExecuteSelect($@"SELECT sn dqsn,outbox_no dqoutbox_no,count dqcount,
  395. update_time dqupdate_time,update_name dqname,rule_name dqrule_name,rule_value dqrule_value
  396. FROM g_packing_sncheck {filterStr.ToString()} ORDER BY update_time desc");
  397. this.Invoke(new Action(() =>
  398. {
  399. QDDatas.DataSource = dt;
  400. }));
  401. });
  402. }
  403. else
  404. {
  405. Loading LoadingForm = new Loading(filterStr.ToString());
  406. if (LoadingForm.ShowDialog() == DialogResult.OK)
  407. {
  408. DataTable dt = LoadingForm.ResultData;
  409. QDDatas.DataSource = dt;
  410. }
  411. }
  412. }
  413. private void QDexport_Click(object sender, EventArgs e)
  414. {
  415. if(QDDatas.Rows.Count == 0)
  416. {
  417. MessageBox.Show("请先查询出导出数据", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  418. return;
  419. }
  420. if (string.IsNullOrEmpty(settingRightInput2.Text))
  421. {
  422. MessageBox.Show("请先在设置中选择导出路径", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  423. return;
  424. }
  425. Application excelApp = null;
  426. Workbook workbook = null;
  427. Worksheet worksheet = null;
  428. Range range = null;
  429. string tempTemplatePath = null;
  430. try
  431. {
  432. string exportPath = Path.Combine(settingRightInput2.Text, DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss") + ".xlsx");
  433. if (string.IsNullOrEmpty(settingRightInput2.Text) || !Directory.Exists(settingRightInput2.Text))
  434. {
  435. MessageBox.Show($"输出目录不存在: {settingRightInput2.Text}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  436. return;
  437. }
  438. byte[] templateBytes = Resources.exportModel; // 假设Resources.exportModel是有效的资源
  439. if (templateBytes == null || templateBytes.Length == 0)
  440. {
  441. MessageBox.Show("未能加载模板文件", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  442. return;
  443. }
  444. tempTemplatePath = Path.GetTempFileName().Replace(".tmp", ".xlsx");
  445. File.WriteAllBytes(tempTemplatePath, templateBytes);
  446. excelApp = new Application();
  447. excelApp.Visible = false;
  448. excelApp.DisplayAlerts = false;
  449. workbook = excelApp.Workbooks.Open(tempTemplatePath);
  450. object sheetIndex = 1;
  451. worksheet = (Worksheet)workbook.Worksheets[sheetIndex];
  452. int startRow = 2;
  453. int dataRowsCount = QDDatas.Rows.Count;
  454. for (int i = 0; i < QDDatas.Rows.Count; i++)
  455. {
  456. worksheet.Cells[startRow + i, 1] = i + 1; // 改为从1开始编号,更符合Excel习惯
  457. worksheet.Cells[startRow + i, 2] = QDDatas.Rows[i].Cells[0].Value?.ToString();
  458. }
  459. int endRow = startRow + dataRowsCount - 1;
  460. range = worksheet.Range[worksheet.Cells[startRow, 1], worksheet.Cells[endRow, 2]];
  461. range.HorizontalAlignment = XlHAlign.xlHAlignCenter; // 水平居中
  462. range.VerticalAlignment = XlVAlign.xlVAlignCenter; // 垂直居中
  463. worksheet.Columns.AutoFit();
  464. // 修复SaveAs方法,使用正确的参数
  465. workbook.SaveAs(
  466. Filename: exportPath,
  467. FileFormat: XlFileFormat.xlOpenXMLWorkbook,
  468. Password: Type.Missing,
  469. WriteResPassword: Type.Missing,
  470. ReadOnlyRecommended: Type.Missing,
  471. CreateBackup: Type.Missing,
  472. AccessMode: XlSaveAsAccessMode.xlExclusive,
  473. ConflictResolution: Type.Missing,
  474. AddToMru: false,
  475. TextCodepage: Type.Missing,
  476. TextVisualLayout: Type.Missing,
  477. Local: Type.Missing
  478. );
  479. MessageBox.Show($"Excel文件已成功导出到: {exportPath}", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
  480. }
  481. catch (Exception ex)
  482. {
  483. MessageBox.Show($"生成 Excel 文件时出错: {ex.Message}", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  484. }
  485. finally
  486. {
  487. // 正确释放COM对象
  488. if (worksheet != null)
  489. {
  490. try
  491. {
  492. Marshal.ReleaseComObject(worksheet);
  493. }
  494. catch { }
  495. worksheet = null;
  496. }
  497. if (workbook != null)
  498. {
  499. try
  500. {
  501. workbook.Close(false);
  502. Marshal.ReleaseComObject(workbook);
  503. }
  504. catch { }
  505. workbook = null;
  506. }
  507. if (excelApp != null)
  508. {
  509. try
  510. {
  511. excelApp.Quit();
  512. Marshal.ReleaseComObject(excelApp);
  513. }
  514. catch { }
  515. excelApp = null;
  516. }
  517. if (!string.IsNullOrEmpty(tempTemplatePath) && File.Exists(tempTemplatePath))
  518. {
  519. try
  520. {
  521. File.Delete(tempTemplatePath);
  522. }
  523. catch (Exception ex)
  524. {
  525. }
  526. }
  527. GC.Collect();
  528. GC.WaitForPendingFinalizers();
  529. }
  530. }
  531. private void rulesAdd_Click(object sender, EventArgs e)
  532. {
  533. StringBuilder filterStr = new StringBuilder();
  534. if (!string.IsNullOrEmpty(rulesInput1.Text))
  535. {
  536. filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0");
  537. }
  538. if (!string.IsNullOrEmpty(rulesInput2.Text))
  539. {
  540. if(filterStr.Length == 0)
  541. {
  542. filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0");
  543. }
  544. else
  545. {
  546. filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0");
  547. }
  548. }
  549. Form rulesList = new RulesList("Add",_UserName);
  550. if (rulesList.ShowDialog() == DialogResult.OK)
  551. {
  552. MessageBox.Show("新增规则成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  553. dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3,
  554. RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc");
  555. RulesDatas.DataSource = dt;
  556. }
  557. }
  558. private void rulesQuery_Click(object sender, EventArgs e)
  559. {
  560. StringBuilder filterStr = new StringBuilder();
  561. if (!string.IsNullOrEmpty(rulesInput1.Text))
  562. {
  563. filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0");
  564. }
  565. if (!string.IsNullOrEmpty(rulesInput2.Text))
  566. {
  567. if (filterStr.Length == 0)
  568. {
  569. filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0");
  570. }
  571. else
  572. {
  573. filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0");
  574. }
  575. }
  576. dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3,
  577. RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc");
  578. RulesDatas.DataSource = dt;
  579. }
  580. private void RulesDatas_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
  581. {
  582. if (e.RowIndex >= 0 && !RulesDatas.Rows[e.RowIndex].IsNewRow)
  583. {
  584. DataGridView dgv = sender as DataGridView;
  585. if (dgv != null)
  586. {
  587. DataGridViewRow selectedRow = dgv.Rows[e.RowIndex];
  588. string RULE_ID = selectedRow.Cells[0].Value.ToString();
  589. StringBuilder filterStr = new StringBuilder();
  590. if (!string.IsNullOrEmpty(rulesInput1.Text))
  591. {
  592. filterStr.Append($"WHERE instr(RULE_NAME,'{rulesInput1.Text}') > 0");
  593. }
  594. if (!string.IsNullOrEmpty(rulesInput2.Text))
  595. {
  596. if (filterStr.Length == 0)
  597. {
  598. filterStr.Append($"WHERE instr(RULE_VALUE,'{rulesInput2.Text}') > 0");
  599. }
  600. else
  601. {
  602. filterStr.Append($" and instr(RULE_VALUE, '{rulesInput2.Text}') > 0");
  603. }
  604. }
  605. Form rulesList = new RulesList("Modify",RULE_ID, _UserName);
  606. if (rulesList.ShowDialog() == DialogResult.OK)
  607. {
  608. MessageBox.Show("修改规则成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  609. dt = ConnectDB.ExecuteSelect($@"SELECT RULE_ID ruleId,RULE_NAME RulesCol1, RULE_VALUE RulesCol2, RELE_REMARK RulesCol3,
  610. RULE_LENGTH RulesCol4,to_char(UPDATE_TIME, 'YYYY-MM-DD HH:Mi:SS') RulesCol5,UPDATE_USER RulesCol6 FROM g_packing_rules {filterStr.ToString()} order by UPDATE_TIME desc");
  611. RulesDatas.DataSource = dt;
  612. }
  613. }
  614. }
  615. }
  616. private void RulesDatas_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)
  617. {
  618. if (e.RowIndex >= 0 && !RulesDatas.Rows[e.RowIndex].IsNewRow)
  619. {
  620. DataGridView dgv = sender as DataGridView;
  621. if (dgv != null)
  622. {
  623. DataGridViewRow selectedRow = dgv.Rows[e.RowIndex];
  624. if (dRules.Enabled)
  625. {
  626. dRules.Text = selectedRow.Cells[1].Value.ToString();
  627. curRuleId = selectedRow.Cells[0].Value.ToString();
  628. curRule = selectedRow.Cells[2].Value.ToString();
  629. curRuleLeng = selectedRow.Cells[4].Value.ToString();
  630. }
  631. }
  632. }
  633. }
  634. private void boxBtn_Click(object sender, EventArgs e)
  635. {
  636. BoxNo.Enabled = true;
  637. BoxNo.Focus();
  638. BoxNo.SelectAll();
  639. }
  640. private void settingRightInput1_Click(object sender, EventArgs e)
  641. {
  642. using (OpenFileDialog openFileDialog = new OpenFileDialog())
  643. {
  644. openFileDialog.Title = "请选择告警文件";
  645. openFileDialog.Filter = "可执行文件 (*.wav)|*.wav|所有文件 (*.*)|*.*";
  646. openFileDialog.FilterIndex = 1;
  647. openFileDialog.RestoreDirectory = true;
  648. if (!string.IsNullOrEmpty(settingRightInput1.Text) && System.IO.File.Exists(settingRightInput1.Text))
  649. {
  650. openFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(settingRightInput1.Text);
  651. }
  652. else
  653. {
  654. openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
  655. }
  656. if (openFileDialog.ShowDialog() == DialogResult.OK)
  657. {
  658. settingRightInput1.Text = openFileDialog.FileName;
  659. }
  660. }
  661. }
  662. private void settingRightInput2_Click(object sender, EventArgs e)
  663. {
  664. using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
  665. {
  666. folderBrowserDialog.Description = "请选择导出文件夹";
  667. if (!string.IsNullOrEmpty(settingRightInput2.Text) && System.IO.Directory.Exists(settingRightInput2.Text))
  668. {
  669. folderBrowserDialog.SelectedPath = settingRightInput2.Text;
  670. }
  671. else
  672. {
  673. folderBrowserDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // folderBrowserDialog.SelectedPath = "";
  674. }
  675. if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
  676. {
  677. settingRightInput2.Text = folderBrowserDialog.SelectedPath;
  678. }
  679. }
  680. }
  681. private void QDdtp1_ValueChanged(object sender, EventArgs e)
  682. {
  683. if (QDdtp1.Value > QDdtp2.Value)
  684. {
  685. QDdtp1.Value = QDdtp2.Value.AddDays(-1);
  686. MessageBox.Show("时间不得大于最大时间", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  687. return;
  688. }
  689. minTime = QDdtp1.Value.ToString("yyyy-mm-dd hh:mm:ss");
  690. }
  691. private void DRulesBtn_Click(object sender, EventArgs e)
  692. {
  693. if (string.IsNullOrEmpty(dRules.Text))
  694. {
  695. MessageBox.Show("请选择条码规则", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  696. return;
  697. }
  698. dRules.Enabled = false;
  699. }
  700. private void DRulesBtn1_Click(object sender, EventArgs e)
  701. {
  702. dRules.Enabled = true;
  703. }
  704. private void QDdtp2_ValueChanged(object sender, EventArgs e)
  705. {
  706. if (QDdtp2.Value < QDdtp1.Value)
  707. {
  708. QDdtp2.Value = QDdtp1.Value.AddDays(1);
  709. MessageBox.Show("时间不得小于最小时间", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  710. return;
  711. }
  712. maxTime = QDdtp2.Value.ToString("yyyy-mm-dd hh:mm:ss");
  713. }
  714. private void PlaySound(string type)
  715. {
  716. if (type == "OK")
  717. {
  718. ShowMsg.Text = "Pass";
  719. ShowMsg.BackColor = Color.LawnGreen;
  720. }
  721. else
  722. {
  723. ShowMsg.Text = "Fail";
  724. ShowMsg.BackColor = Color.Red;
  725. }
  726. Task.Run(() => {
  727. if (type == "OK")
  728. {
  729. using (var stream = UAS_Tools_HY.Properties.Resources.OK)
  730. {
  731. SoundPlayer player = new SoundPlayer(stream);
  732. player.Play();
  733. }
  734. }
  735. else
  736. {
  737. if (string.IsNullOrEmpty(settingRightInput1.Text))
  738. {
  739. using (var stream = UAS_Tools_HY.Properties.Resources.NG)
  740. {
  741. SoundPlayer player = new SoundPlayer(stream);
  742. player.Play();
  743. }
  744. }
  745. else
  746. {
  747. string customPath = settingRightInput1.Text.Trim();
  748. if (File.Exists(customPath))
  749. {
  750. SoundPlayer player = new SoundPlayer(customPath);
  751. player.Play();
  752. }
  753. }
  754. }
  755. });
  756. }
  757. public void loadTime_Tick(object sender, EventArgs e)
  758. {
  759. string currentDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
  760. currTime.Text = currentDate;
  761. handTime.Value = new DateTime(DateTime.Now.Year,DateTime.Now.Month,DateTime.Now.Day,DateTime.Now.Hour,0, 0);
  762. }
  763. private async void FtpConnect_Click(object sender, EventArgs e)
  764. {
  765. if(FtpConnect.Text == "开启连接")
  766. {
  767. if (string.IsNullOrEmpty(FtpAccountVal.Text))
  768. {
  769. LogMessage("NG,请填写ftp账户");
  770. return;
  771. }
  772. if (string.IsNullOrEmpty(FtpPwVal.Text))
  773. {
  774. LogMessage("NG,请填写ftp密码");
  775. return;
  776. }
  777. if (string.IsNullOrEmpty(timerVal.Text))
  778. {
  779. LogMessage("NG,请填写间隔抓取文件时间");
  780. return;
  781. }
  782. if (string.IsNullOrEmpty(FtpPathVal.Text))
  783. {
  784. LogMessage("NG,请填写ftp抓取路径地址");
  785. return;
  786. }
  787. if (string.IsNullOrEmpty(FileCountVal.Text))
  788. {
  789. LogMessage("NG,请填写打包文件数");
  790. return;
  791. }
  792. FtpConnect.Enabled = false;
  793. FtpConnect.Text = "连接中...";
  794. LogMessage("开始测试连接...");
  795. bool testConnect = await TestFtpConnection(FtpPathVal.Text.Trim(), FtpAccountVal.Text.Trim(), FtpPwVal.Text.Trim());
  796. if (testConnect)
  797. {
  798. FtpAccountVal.Enabled = false;
  799. FtpPwVal.Enabled = false;
  800. timerVal.Enabled = false;
  801. FtpPathVal.Enabled = false;
  802. FileCountVal.Enabled = false;
  803. FtpConnect.Text = "关闭连接";
  804. FtpListen.Enabled = true;
  805. }
  806. else
  807. {
  808. FtpConnect.Enabled = true;
  809. FtpConnect.Text = "开启连接";
  810. }
  811. }
  812. else if(FtpConnect.Text == "关闭连接")
  813. {
  814. FtpAccountVal.Enabled = true;
  815. FtpPwVal.Enabled = true;
  816. timerVal.Enabled = true;
  817. FtpPathVal.Enabled = true;
  818. FileCountVal.Enabled = true;
  819. FtpConnect.Text = "开启连接";
  820. FtpListen.Enabled = false;
  821. }
  822. }
  823. public async Task<bool> TestFtpConnection(string ftpServer, string username, string password)
  824. {
  825. try
  826. {
  827. var request = (FtpWebRequest)WebRequest.Create(ftpServer);
  828. request.Method = WebRequestMethods.Ftp.ListDirectory;
  829. request.Credentials = new NetworkCredential(username, password);
  830. request.UsePassive = true;
  831. request.UseBinary = true;
  832. request.KeepAlive = false;
  833. request.Timeout = 10000;
  834. using (var response = await request.GetResponseAsync() as FtpWebResponse)
  835. {
  836. await Task.Run(() =>
  837. {
  838. LogMessage($"OK,FTP连接成功: {response.StatusDescription}");
  839. });
  840. return true;
  841. }
  842. }
  843. catch (WebException ex)
  844. {
  845. await Task.Run(() =>
  846. {
  847. if (ex.Response is FtpWebResponse response)
  848. {
  849. LogMessage($"NG,FTP连接失败,错误码: {(int)response.StatusCode} - {response.StatusDescription}");
  850. }
  851. else
  852. {
  853. LogMessage("NG,连接异常: " + ex.Message);
  854. }
  855. });
  856. return false;
  857. }
  858. catch (Exception ex)
  859. {
  860. await Task.Run(() =>
  861. {
  862. LogMessage($"NG,连接失败: " + ex.Message);
  863. });
  864. return false;
  865. }
  866. }
  867. private void FtpListen_Click(object sender, EventArgs e)
  868. {
  869. File_timer.Interval = Convert.ToInt32(timerVal.Text.Trim()) * 1000;
  870. if (FtpListen.Text == "开启监听")
  871. {
  872. FtpListen.Text = "关闭监听";
  873. FtpConnect.Enabled = false;
  874. File_timer.Start();
  875. Timer_Tick(null, null);
  876. }
  877. else if (FtpListen.Text == "关闭监听")
  878. {
  879. FtpListen.Text = "开启监听";
  880. FtpConnect.Enabled = true;
  881. File_timer.Stop();
  882. }
  883. }
  884. private void MsgBox_DrawItem(object sender, DrawItemEventArgs e)
  885. {
  886. e.DrawBackground();
  887. Brush mybsh = Brushes.Black;
  888. string msgStr = MsgBox.Items[e.Index].ToString();
  889. Console.WriteLine();
  890. if (MsgBox.Items[e.Index].ToString().Contains("OK"))
  891. {
  892. mybsh = Brushes.Green;
  893. }
  894. else if (MsgBox.Items[e.Index].ToString().Contains("NG"))
  895. {
  896. mybsh = Brushes.Red;
  897. }
  898. e.DrawFocusRectangle();
  899. e.Graphics.DrawString(MsgBox.Items[e.Index].ToString(), e.Font, mybsh, e.Bounds, StringFormat.GenericDefault);
  900. }
  901. private void LogMessage(string message)
  902. {
  903. if (MsgBox.InvokeRequired)
  904. {
  905. MsgBox.Invoke(new Action<string>(LogMessage), message);
  906. return;
  907. }
  908. MsgBox.Items.Add($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
  909. MsgBox.TopIndex = MsgBox.Items.Count - 1;
  910. MsgBox.DrawMode = DrawMode.OwnerDrawFixed;
  911. }
  912. private void Timer_Tick(object sender, EventArgs e)
  913. {
  914. try
  915. {
  916. string childSaveFiles = Path.Combine(saveFiles, DateTime.Now.ToString("yyyyMMdd"));
  917. if (!Directory.Exists(childSaveFiles))
  918. {
  919. Directory.CreateDirectory(childSaveFiles);
  920. currentNum = 1;
  921. LogMessage($"创建本地文件夹: {childSaveFiles}");
  922. }
  923. string ftpServer = FtpPathVal.Text.Trim();
  924. string remoteFolderPath = "";
  925. string username = FtpAccountVal.Text.Trim();
  926. string password = FtpPwVal.Text.Trim();
  927. List<string> fileList = GetFtpFileList(ftpServer, remoteFolderPath, username, password);
  928. if (fileList.Count == 0)
  929. {
  930. LogMessage($"远程文件夹 '{remoteFolderPath}' 中没有文件");
  931. return;
  932. }
  933. int successCount = 0;
  934. int failCount = 0;
  935. LogMessage($"开始下载 {fileList.Count} 个文件...");
  936. foreach (string remoteFile in fileList)
  937. {
  938. if (!Directory.Exists(childSaveFiles))
  939. {
  940. Directory.CreateDirectory(childSaveFiles);
  941. }
  942. string remoteFilePath = $"{remoteFolderPath.TrimEnd('/')}/{remoteFile}";
  943. string localFilePath = Path.Combine(childSaveFiles, remoteFile);
  944. if (DownloadSingleFile(ftpServer, remoteFilePath, localFilePath, username, password))
  945. {
  946. successCount++;
  947. }
  948. else
  949. {
  950. failCount++;
  951. }
  952. string[] files = Directory.GetFiles(childSaveFiles);
  953. string zipFilePath = Path.Combine(Path.GetDirectoryName(childSaveFiles), Path.GetFileName(childSaveFiles) + $"-{currentNum}.zip");
  954. if (Convert.ToInt32(FileCountVal.Text.Trim()) == files.Length)
  955. {
  956. CompressFolder(childSaveFiles, zipFilePath);
  957. currentNum++;
  958. }
  959. }
  960. LogMessage($"下载完成: 成功 {successCount} 个, 失败 {failCount} 个");
  961. }
  962. catch (Exception ex)
  963. {
  964. LogMessage($"NG,自动获取文件失败,Error: {ex.Message}");
  965. }
  966. }
  967. private List<string> GetFtpFileList(string ftpServer, string folderPath, string username, string password)
  968. {
  969. List<string> fileList = new List<string>();
  970. try
  971. {
  972. string uri = $"{ftpServer.TrimEnd('/')}/{folderPath.TrimStart('/')}";
  973. var request = (FtpWebRequest)WebRequest.Create(uri);
  974. request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
  975. request.Credentials = new NetworkCredential(username, password);
  976. request.UsePassive = true;
  977. request.UseBinary = true;
  978. request.KeepAlive = false;
  979. using (var response = (FtpWebResponse)request.GetResponse())
  980. using (var responseStream = response.GetResponseStream())
  981. using (var reader = new StreamReader(responseStream))
  982. {
  983. string line;
  984. while ((line = reader.ReadLine()) != null)
  985. {
  986. if (!string.IsNullOrWhiteSpace(line))
  987. {
  988. string[] parts = line.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
  989. if (parts.Length >= 3)
  990. {
  991. //string fileName = parts[8];
  992. //if (!parts[0].StartsWith("d") && fileName != "." && fileName != "..")
  993. //{
  994. // fileList.Add(fileName);
  995. //}
  996. string fileName = parts[parts.Length - 1];
  997. if (fileName.Contains("."))
  998. {
  999. fileList.Add(fileName);
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. }
  1006. catch (Exception ex)
  1007. {
  1008. LogMessage($"获取文件列表失败: {ex.Message}");
  1009. }
  1010. return fileList;
  1011. }
  1012. private bool DownloadSingleFile(string ftpServer, string remoteFilePath, string localFilePath, string username, string password)
  1013. {
  1014. try
  1015. {
  1016. bool downloadSuccess = false;
  1017. string uri = $"{ftpServer.TrimEnd('/')}/{remoteFilePath.TrimStart('/')}";
  1018. var request = (FtpWebRequest)WebRequest.Create(uri);
  1019. request.Method = WebRequestMethods.Ftp.DownloadFile;
  1020. request.Credentials = new NetworkCredential(username, password);
  1021. request.UsePassive = true;
  1022. request.UseBinary = true;
  1023. request.KeepAlive = false;
  1024. using (var response = (FtpWebResponse)request.GetResponse())
  1025. using (var responseStream = response.GetResponseStream())
  1026. using (var fileStream = File.Create(localFilePath))
  1027. {
  1028. byte[] buffer = new byte[4096];
  1029. int bytesRead;
  1030. while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
  1031. {
  1032. fileStream.Write(buffer, 0, bytesRead);
  1033. }
  1034. downloadSuccess = true;
  1035. LogMessage($"OK,文件下载成功: {remoteFilePath} -> {localFilePath}");
  1036. if (downloadSuccess)
  1037. {
  1038. var deleteRequest = (FtpWebRequest)WebRequest.Create(uri);
  1039. deleteRequest.Method = WebRequestMethods.Ftp.DeleteFile;
  1040. deleteRequest.Credentials = new NetworkCredential(username, password);
  1041. deleteRequest.UsePassive = true;
  1042. deleteRequest.KeepAlive = false;
  1043. using (var deleteResponse = (FtpWebResponse)deleteRequest.GetResponse())
  1044. {
  1045. LogMessage($"OK,服务器文件删除成功: {remoteFilePath}");
  1046. }
  1047. }
  1048. return true;
  1049. }
  1050. }
  1051. catch (WebException ex)
  1052. {
  1053. if (ex.Response is FtpWebResponse response)
  1054. {
  1055. LogMessage($"NG,下载失败 {remoteFilePath}: {(int)response.StatusCode} - {response.StatusDescription}");
  1056. }
  1057. else
  1058. {
  1059. LogMessage($"NG,下载失败 {remoteFilePath}: {ex.Message}");
  1060. }
  1061. return false;
  1062. }
  1063. catch (Exception ex)
  1064. {
  1065. LogMessage($"NG,下载失败 {remoteFilePath}: {ex.Message}");
  1066. return false;
  1067. }
  1068. }
  1069. private string CreateFtpDirectoryIfNotExists(string ftpDirectoryPath, string username, string password)
  1070. {
  1071. try
  1072. {
  1073. FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpDirectoryPath);
  1074. request.Method = WebRequestMethods.Ftp.MakeDirectory;
  1075. request.Credentials = new NetworkCredential(username, password);
  1076. request.UsePassive = true;
  1077. request.UseBinary = true;
  1078. request.KeepAlive = false;
  1079. using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
  1080. {
  1081. response.Close();
  1082. return "OK,目录创建成功: " + response.StatusDescription;
  1083. }
  1084. }
  1085. catch (WebException ex)
  1086. {
  1087. if (ex.Response is FtpWebResponse response && response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
  1088. {
  1089. return "OK,目录已存在: " + response.StatusDescription;
  1090. }
  1091. else
  1092. {
  1093. return "NG,创建目录时发生错误: " + ex.Message;
  1094. }
  1095. }
  1096. }
  1097. private void CompressFile(string sourceFile, string zipPath)
  1098. {
  1099. try
  1100. {
  1101. using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create))
  1102. using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
  1103. {
  1104. string fileName = Path.GetFileName(sourceFile);
  1105. ZipArchiveEntry readmeEntry = archive.CreateEntry(fileName);
  1106. using (Stream stream = readmeEntry.Open())
  1107. using (FileStream fileStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read))
  1108. {
  1109. fileStream.CopyTo(stream);
  1110. }
  1111. }
  1112. LogMessage($"OK,文件已压缩到:{zipPath}");
  1113. }
  1114. catch (Exception ex)
  1115. {
  1116. LogMessage($"NG,压缩失败:{ex.Message}");
  1117. }
  1118. }
  1119. private void CompressFolder(string sourceFolder, string zipPath)
  1120. {
  1121. try
  1122. {
  1123. if (File.Exists(zipPath))
  1124. {
  1125. try
  1126. {
  1127. File.Delete(zipPath);
  1128. }
  1129. catch (IOException ex)
  1130. {
  1131. LogMessage($"NG,无法删除已存在的文件,可能被其他程序占用:{ex.Message}");
  1132. return;
  1133. }
  1134. catch (UnauthorizedAccessException ex)
  1135. {
  1136. LogMessage($"NG,没有权限删除文件:{ex.Message}");
  1137. return;
  1138. }
  1139. }
  1140. ZipFile.CreateFromDirectory(sourceFolder, zipPath);
  1141. Directory.Delete(sourceFolder, true);
  1142. LogMessage($"OK,文件已压缩到:{zipPath}");
  1143. }
  1144. catch (UnauthorizedAccessException ex)
  1145. {
  1146. LogMessage($"NG,访问被拒绝:{ex.Message}");
  1147. }
  1148. catch (Exception ex)
  1149. {
  1150. LogMessage($"NG,压缩失败:{ex.Message}");
  1151. }
  1152. }
  1153. private void listenVal_Click(object sender, EventArgs e)
  1154. {
  1155. using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
  1156. {
  1157. folderDialog.Description = "请选择监控文件夹";
  1158. folderDialog.SelectedPath = listenVal.Text;
  1159. if (folderDialog.ShowDialog() == DialogResult.OK)
  1160. {
  1161. listenVal.Text = folderDialog.SelectedPath;
  1162. }
  1163. }
  1164. }
  1165. private void handPathVal_Click(object sender, EventArgs e)
  1166. {
  1167. using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
  1168. {
  1169. folderDialog.Description = "请选择导出文件夹";
  1170. folderDialog.SelectedPath = handPathVal.Text;
  1171. if (folderDialog.ShowDialog() == DialogResult.OK)
  1172. {
  1173. handPathVal.Text = folderDialog.SelectedPath;
  1174. }
  1175. }
  1176. }
  1177. private void buildConfirm_Click(object sender, EventArgs e)
  1178. {
  1179. if (buildConfirm.Text == "确定")
  1180. {
  1181. if (string.IsNullOrEmpty(handExeVal.Text))
  1182. {
  1183. LogMessage($"NG,请填写处理间隔时间");
  1184. return;
  1185. }
  1186. if (string.IsNullOrEmpty(listenVal.Text))
  1187. {
  1188. LogMessage($"NG,请填写监控路径");
  1189. return;
  1190. }
  1191. if (string.IsNullOrEmpty(handPathVal.Text))
  1192. {
  1193. LogMessage($"NG,请填写导出路径");
  1194. return;
  1195. }
  1196. handExeVal.Enabled = false;
  1197. handTime.Enabled = false;
  1198. listenVal.Enabled = false;
  1199. handPathVal.Enabled = false;
  1200. buildConfirm.Text = "取消";
  1201. }
  1202. else
  1203. {
  1204. handExeVal.Enabled = true;
  1205. handTime.Enabled = true;
  1206. listenVal.Enabled = true;
  1207. handPathVal.Enabled = true;
  1208. buildConfirm.Text = "确定";
  1209. }
  1210. }
  1211. private void buildStart_Click(object sender, EventArgs e)
  1212. {
  1213. if(buildStart.Text == "开启处理")
  1214. {
  1215. buildStart.Text = "关闭处理";
  1216. File_timer1.Interval = Convert.ToInt32(handExeVal.Text) * 60 * 1000;
  1217. File_timer1.Start();
  1218. FileTimer_Tick(null, null);
  1219. }
  1220. else
  1221. {
  1222. buildStart.Text = "开启处理";
  1223. File_timer.Stop();
  1224. }
  1225. }
  1226. private async void FileTimer_Tick(object sender, EventArgs e)
  1227. {
  1228. _currentOperationCts?.Cancel();
  1229. _currentOperationCts = new CancellationTokenSource();
  1230. try
  1231. {
  1232. await Task.Run(() => ProcessFilesInternal(_currentOperationCts.Token));
  1233. }
  1234. catch (OperationCanceledException)
  1235. {
  1236. LogMessage("文件处理操作被新任务取消。");
  1237. }
  1238. catch (Exception ex)
  1239. {
  1240. LogMessage($"NG,定时器任务启动失败: {ex}");
  1241. }
  1242. /*try
  1243. {
  1244. string[] txtFiles = Directory.GetFiles(listenVal.Text, $"*.json");
  1245. string currentHour = DateTime.Now.ToString("yyyyMMdd_hh");
  1246. string outPath = Path.Combine(handPathVal.Text, currentHour + "_Count_" + txtFiles.Length);
  1247. if (!Directory.Exists(outPath))
  1248. {
  1249. Directory.CreateDirectory(outPath);
  1250. }
  1251. foreach (string file in txtFiles)
  1252. {
  1253. string targetFile = Path.Combine(outPath, Path.GetFileName(file));
  1254. if (File.Exists(targetFile))
  1255. {
  1256. File.Delete(targetFile);
  1257. }
  1258. File.Move(file, targetFile);
  1259. }
  1260. string zipPath = outPath + ".zip";
  1261. if (File.Exists(zipPath))
  1262. {
  1263. File.Delete(zipPath);
  1264. }
  1265. ZipFile.CreateFromDirectory(outPath, zipPath);
  1266. LogMessage($"OK,文件已压缩到:{zipPath}");
  1267. }
  1268. catch(Exception ex)
  1269. {
  1270. LogMessage($"NG,解析文件列表失败: {ex.Message}");
  1271. }*/
  1272. }
  1273. private void ProcessFilesInternal(CancellationToken cancellationToken)
  1274. {
  1275. try
  1276. {
  1277. var txtFiles = Directory.EnumerateFiles(listenVal.Text, "*.json", SearchOption.TopDirectoryOnly).ToList();
  1278. int fileCount = txtFiles.Count;
  1279. if (fileCount == 0)
  1280. {
  1281. LogMessage("没有找到需要处理的 .json 文件。");
  1282. return;
  1283. }
  1284. cancellationToken.ThrowIfCancellationRequested();
  1285. LogMessage($"已找到找到 {fileCount} 个json文件,开始处理...");
  1286. string currentHour = DateTime.Now.ToString("yyyyMMdd_HH");
  1287. string outPath = Path.Combine(handPathVal.Text, $"{currentHour}_{Convert.ToInt32(handExeVal.Text)}_Count_{fileCount}");
  1288. cancellationToken.ThrowIfCancellationRequested();
  1289. if (!Directory.Exists(outPath))
  1290. {
  1291. Directory.CreateDirectory(outPath);
  1292. }
  1293. int movedCount = 0;
  1294. foreach (string file in txtFiles)
  1295. {
  1296. cancellationToken.ThrowIfCancellationRequested();
  1297. string targetFile = Path.Combine(outPath, Path.GetFileName(file));
  1298. if (File.Exists(targetFile))
  1299. {
  1300. File.Delete(targetFile);
  1301. }
  1302. File.Move(file, targetFile);
  1303. movedCount++;
  1304. if (movedCount % 1000 == 0)
  1305. {
  1306. LogMessage($"已移动 {movedCount}/{fileCount} 个文件...");
  1307. }
  1308. }
  1309. LogMessage($"成功移动 {movedCount} 个文件到 '{outPath}'");
  1310. string zipPath = outPath + ".zip";
  1311. cancellationToken.ThrowIfCancellationRequested();
  1312. if (File.Exists(zipPath))
  1313. {
  1314. File.Delete(zipPath);
  1315. }
  1316. ZipFile.CreateFromDirectory(outPath, zipPath);
  1317. //Directory.Delete(outPath, true);
  1318. LogMessage($"OK, {fileCount} 个文件已成功压缩到: {zipPath}");
  1319. }
  1320. catch (OperationCanceledException)
  1321. {
  1322. LogMessage("OK, 文件处理操作被用户取消。");
  1323. }
  1324. catch (UnauthorizedAccessException ex)
  1325. {
  1326. LogMessage($"NG, 访问被拒绝,可能没有足够权限读写文件或目录: {ex.Message}");
  1327. }
  1328. catch (DirectoryNotFoundException ex)
  1329. {
  1330. LogMessage($"NG, 指定的路径不存在: {ex.Message}");
  1331. }
  1332. catch (IOException ex)
  1333. {
  1334. LogMessage($"NG, 文件 I/O 错误: {ex.Message}");
  1335. }
  1336. catch (Exception ex)
  1337. {
  1338. LogMessage($"NG, 文件处理过程中发生未知错误: {ex}");
  1339. }
  1340. }
  1341. }
  1342. }