using Common; using DevExpress.XtraEditors; using FileModel.UpLoad; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; namespace WinUpload { public partial class FrmUpLoad : XtraForm { #region [上传文件列表] DataTable dt = new DataTable(); private int currentValve = 0; private int maxValve = 0; private string serverFileName; public FrmUpLoad() { InitializeComponent(); LoadListView(); //CloseForm(); } /// <summary> /// 关闭 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PicClose_Click(object sender, EventArgs e) { if (MsgDvUtil.ShowYesNoAndWarning("确定退出本系统?") == DialogResult.Yes) { this.Close(); } } /// <summary> ///窗体加载信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void FrmUpLoad_Load(object sender, EventArgs e) { LoadTxtValues(); } #region 无边窗体移动窗体实现方法 [DllImport("user32.dll")] public static extern bool ReleaseCapture(); [DllImport("user32.dll")] public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam); private const int WM_NCLBUTTONDOWN = 0XA1; //定义鼠标左键按下 private const int HTCAPTION = 2; private void pHeader_MouseDown(object sender, MouseEventArgs e) { ReleaseCapture(); //发送消息,让系统误以为在标题栏上按下鼠标 SendMessage(this.Handle, WM_NCLBUTTONDOWN, HTCAPTION, 0); } #endregion /// <summary> /// 初始化上传列表 /// </summary> void LoadListView() { lstFileList.FullRowSelect = true;//是否选中整行 lstFileList.Scrollable = true;//是否自动显示滚动条 lstFileList.MultiSelect = false;//是否可以选择多行 lstFileList.View = View.Details; lstFileList.CheckBoxes = true; lstFileList.GridLines = true; lstFileList.Columns.Add("FileName", "文件名称"); lstFileList.Columns.Add("FileSize", "文件大小"); lstFileList.Columns.Add("FileType", "文件类型"); lstFileList.Columns.Add("FileDate", "文件日期"); } /// <summary> /// 初始化文本框信息 /// </summary> void LoadTxtValues() { ReadConfigInfo(); } /// <summary> /// 获取文件的路劲 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnSelectFile_Click(object sender, EventArgs e) { lstFileList.Items.Clear(); FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { txtLocalFilePath.Text = fbd.SelectedPath; } if (!string.IsNullOrEmpty(txtLocalFilePath.Text.Trim())) { DirectoryInfo dir = new DirectoryInfo(txtLocalFilePath.Text.Trim()); foreach (FileInfo filename in dir.GetFiles()) { ListViewItem lvi = new ListViewItem(Path.GetFileName(filename.ToString())); //不带后缀名文件名Path.GetFileNameWithoutExtension lvi.Tag = filename; lvi.SubItems.Add(filename.Length.ToString());//文件大小 //lvi.SubItems.Add((fi.Length / (1024 * 1024)).ToString() + "M"); //由于文件太小不便于以M //lvi.SubItems.Add(Path.GetDirectoryName(filename));文件路劲 lvi.SubItems.Add(Path.GetExtension(filename.ToString())); lvi.SubItems.Add(DateTime.Parse(filename.LastWriteTime.ToString()).ToString("yyyy-MM-dd HH:mm:ss")); //写入文件的时间 lstFileList.Items.Add(lvi); lstFileList.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } } else { MsgDvUtil.ShowWarning("选择文件路劲不能为空!"); } } /// <summary> /// 配置参数信息 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnReSet_Click(object sender, EventArgs e) { //存在用户配置文件,自动加载登录信息 try { if (!CheckIsNull()) return; string cfgINI = Application.StartupPath + @"ConfigIniConfigFile.ini"; IniFile ini = new IniFile(cfgINI); ini.IniWriteValue("WinUpload", "ServerIP", txtServerIp.Text.Trim()); ini.IniWriteValue("WinUpload", "UPort", CEncoder.Encode(txtUPort.Text.Trim())); ini.IniWriteValue("WinUpload", "DPort", CEncoder.Encode(txtDPort.Text.Trim())); ini.IniWriteValue("WinUpload", "ServerFileName", txtServerFileName.Text.Trim()); ini.IniWriteValue("WinUpload", "SystemName", txtSystemName.Text.Trim()); ini.IniWriteValue("WinUpload", "OldVersionNo", txtOldVersionNo.Text.Trim()); ini.IniWriteValue("WinUpload", "NewVersionNo", txtNewVersionNo.Text.Trim()); ini.IniWriteValue("WinUpload", "UpdateMemo", txtMemo.Text.Trim()); MsgDvUtil.ShowTips("参数信息配置成功!"); ReadConfigInfo(); } catch (Exception ex) { MsgDvUtil.ShowError("错误信息:" + ex.Message); } } /// <summary> /// 读取配置文件信息 /// </summary> private void ReadConfigInfo() { //存在用户配置文件,自动加载配置信息 string cfgINI = Application.StartupPath + @"ConfigIniConfigFile.ini"; if (File.Exists(cfgINI)) { IniFile ini = new IniFile(cfgINI); txtServerIp.Text = ini.IniReadValue("WinUpload", "ServerIP"); txtUPort.Text = CEncoder.Decode(ini.IniReadValue("WinUpload", "UPort")); txtDPort.Text = CEncoder.Decode(ini.IniReadValue("WinUpload", "DPort")); txtServerFileName.Text = ini.IniReadValue("WinUpload", "ServerFileName"); txtSystemName.Text = ini.IniReadValue("WinUpload", "SystemName"); txtOldVersionNo.Text = ini.IniReadValue("WinUpload", "NewVersionNo"); txtNewVersionNo.Text = (Convert.ToDouble(ini.IniReadValue("WinUpload", "NewVersionNo")) + 0.001).ToString(); txtMemo.Text = ini.IniReadValue("WinUpload", "UpdateMemo"); } } /// <summary> /// 验证相关信息 /// </summary> /// <returns></returns> private bool CheckIsNull() { if (string.IsNullOrEmpty(txtServerIp.Text.Trim())) { MsgDvUtil.ShowWarning("服务器不能为空!"); return false; } if (string.IsNullOrEmpty(txtUPort.Text.Trim())) { MsgDvUtil.ShowWarning("文件上传端口!"); return false; } if (string.IsNullOrEmpty(txtDPort.Text)) { MsgDvUtil.ShowWarning("文件下载端口!"); return false; } if (string.IsNullOrEmpty(txtServerFileName.Text.Trim())) { MsgDvUtil.ShowWarning("服务器文件名不能为空!"); return false; } if (string.IsNullOrEmpty(txtNewVersionNo.Text.Trim())) { MsgDvUtil.ShowWarning("最新版本号不能为空!"); return false; } if (string.IsNullOrEmpty(txtServerIp.Text.Trim())) { MsgDvUtil.ShowWarning("服务器不能为空!"); return false; } //if(string.IsNullOrEmpty(txtLocalFilePath.Text.Trim())) //{ // MsgDvUtil.ShowWarning("本地路劲不能为空!"); // return false; //} return true; } public static void DeleteFolder(string dir) { foreach (string d in Directory.GetFileSystemEntries(dir)) { if (File.Exists(d)) { FileInfo fi = new FileInfo(d); if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1) fi.Attributes = FileAttributes.Normal; File.Delete(d);//直接删除其中的文件 } else { DirectoryInfo dFolder = new DirectoryInfo(d); if (dFolder.GetFiles().Length != 0) { DeleteFolder(dFolder.FullName);////递归删除子文件夹 } Directory.Delete(d); } } } /// <summary> /// 文件上传 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnUpLoad_Click(object sender, EventArgs e) { BtnUpload(); //try //{ // if (string.IsNullOrEmpty(txtLocalFilePath.Text.Trim())) // { // MsgDvUtil.ShowWarning("请选择本地更新目录!"); // } // else // if (lstFileList.CheckedItems.Count <= 0) // { // MsgDvUtil.ShowWarning("请选择上传的文件!"); // } // else // { // //DeleteFolder(txtUpdateDir.Text.ToString());//删除文件及子文件夹 // if (lstFileList.Items.Count > 0) // { // ControlIsUse(false); // int j = 0; // string count = lstFileList.CheckedItems.Count.ToString(); // for (int i = 0; i < lstFileList.Items.Count; i++) // { // if (lstFileList.Items[i].Checked) // { // j++; // string fileName = Path.GetFileName(lstFileList.Items[i].Tag.ToString()); // lblFileContent.Text = string.Format("正在上传文件:[{0}]", lstFileList.Items[i].Text) + ":" + j.ToString() + ":" + count; // //需要更正,获取Ftp路劲 // FileStream des = new FileStream(Path.Combine("", fileName), FileMode.OpenOrCreate, FileAccess.Write); // FileStream fir = new FileStream(Path.Combine(txtLocalFilePath.Text, lstFileList.Items[i].Tag.ToString()), FileMode.Open, FileAccess.Read); // byte[] buffer = new byte[10240]; // int size = 0; int ren = 0; // while (ren < fir.Length) // { // Application.DoEvents(); // size = fir.Read(buffer, 0, buffer.Length); // des.Write(buffer, 0, size); // ren += size; // UpProgress(ren); // } // lstFileList.Items[i].Checked = false; // } // else // { // continue; // } // } // MsgDvUtil.ShowTips("上传成功!"); // ControlIsUse(true); // } // else // { // return; // } // } //} //catch (Exception ex) //{ // //LogHelper.ErrorLog(null, ex); // //LogHelper.InsertDBLog(); //} } /// <summary> /// 控件使用状态 /// </summary> /// <param name="enable"></param> private void ControlIsUse(bool enable) { //txtLocalFilePath.Enabled = enable; //btnSelectFile.Enabled = enable; ////lstFileList.Enabled = enable; //txtNewVersionNo.Enabled = enable; //txtSystemName.Enabled = enable; ////btnReSet.Enabled = enable; //btnUpLoad.Enabled = enable; } public delegate void DeleFile(int position); public void UpProgress(int copy) { if (this.progressBar.InvokeRequired) { this.progressBar.Invoke(new DeleFile(UpProgress), new object[] { copy }); return; } foreach (ListViewItem lvi in lstFileList.CheckedItems) { string total = lvi.SubItems[1].Text; int pro = (int)((float)copy / long.Parse(total) * 100); if (pro <= progressBar.Maximum) { progressBar.Value = pro; progressBar.Text = lblFileContent.Text.Split(':')[0].ToString() + Environment.NewLine + string.Format("上传进度:{0}%", pro) + Environment.NewLine + string.Format("已上传文件数:{0}/{1}", lblFileContent.Text.Split(':')[1].ToString(), lblFileContent.Text.Split(':')[2].ToString()); } } } /// <summary> /// 验证文本框只能输入double类型 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void txtNewVersionNo_KeyPress(object sender, KeyPressEventArgs e) { if ((e.KeyChar != 0x08) && (e.KeyChar != 46) && (e.KeyChar < 0x30 || e.KeyChar > 0x39)) { e.KeyChar = (char)0; } try { string content = ((DevExpress.XtraEditors.TextEdit)sender).Text; if (content != "") { if ((e.KeyChar.ToString() == ".")) { string ss = content + "."; Convert.ToDouble(ss); } } } catch { e.KeyChar = (char)0; } } /// <summary> /// 关闭窗体释放进程 /// </summary> private void CloseForm() { this.FormClosed += (sender, e) => { Application.Exit(); System.Diagnostics.Process pro = System.Diagnostics.Process.GetCurrentProcess(); pro.Kill(); }; } /// <summary> /// 右键菜单操作项 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void cmsFile_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { int selectCount = 0; if (e.ClickedItem.Name == "tmsSelectAll")//全选 { selectCount = lstFileList.Items.Count; foreach (ListViewItem item in lstFileList.Items) { item.Checked = true; } } if (e.ClickedItem.Name == "tmsCancel")//取消 { selectCount = lstFileList.Items.Count; foreach (ListViewItem item in lstFileList.Items) { item.Checked = false; } } if (e.ClickedItem.Name == "tmsDelete") //移除 { if (lstFileList.CheckedItems.Count > 0) { foreach (ListViewItem lvi in lstFileList.CheckedItems) { lvi.Remove(); } } else { MsgDvUtil.ShowTips("未选中文件,请选择在移除!"); } } } #endregion /// <summary> /// 获取选中项目文件大小 /// </summary> /// <returns>返回值</returns> private long GetUpdateSize() { long len = 0; if (this.lstFileList.Items.Count > 0) { for (int i = 0; i < lstFileList.Items.Count; i++) { if (lstFileList.Items[i].Checked) { len += long.Parse(lstFileList.Items[i].SubItems[1].Text); } } } return len; } /// <summary> ///获取选中列表配置更新列表 /// </summary> /// <returns></returns> private string[] GetListToXml() { string[] strListArray = null; string strListArrayToXml = null; if (lstFileList.Items.Count > 0) { for (int i = 0; i < lstFileList.Items.Count; i++) { if (lstFileList.Items[i].Checked) { strListArrayToXml += lstFileList.Items[i].Tag.ToString() + ','; } if (strListArrayToXml != null) { strListArray = strListArrayToXml.TrimEnd(',').Split(','); } } return strListArray; } return strListArray; } /// <summary> /// 更新配置文件 /// </summary> /// <param name="strArray"></param> private void BuildUpdateListXml(string[] strArray) { if (strArray != null) { try { XmlDocument xmlDoc = new XmlDocument(); // 创建根节点AutoUpdater XmlElement xeRoot = xmlDoc.CreateElement("AutoUpdater"); xmlDoc.AppendChild(xeRoot); // 加入到上层节点 // 创建UpdateInfo元素 XmlElement xeUI = xmlDoc.CreateElement("UpdateInfo"); xeRoot.AppendChild(xeUI); // 创建UpdateTime元素 XmlElement xeUT = xmlDoc.CreateElement("UpdateTime"); xeUT.SetAttribute("Date", DateTime.Today.ToShortDateString()); xeUI.AppendChild(xeUT); // 创建Version元素 XmlElement xeUV = xmlDoc.CreateElement("Version"); xeUV.SetAttribute("Num", txtNewVersionNo.Text.ToString()); xeUI.AppendChild(xeUV); // 创建UpdateSize元素 XmlElement xeUS = xmlDoc.CreateElement("UpdateSize"); xeUS.SetAttribute("Size", GetUpdateSize().ToString()); xeUI.AppendChild(xeUS); // 创建UpdateFileList元素 XmlElement xeUFL = xmlDoc.CreateElement("UpdateFileList"); xeRoot.AppendChild(xeUFL); for (int i = 0; i < strArray.Length; i++) { // 循环创建UpdateFile元素 XmlElement xeUF = xmlDoc.CreateElement("UpdateFile"); xeUF.InnerText = strArray[i]; xeUFL.AppendChild(xeUF); // 加入到上层节点 } xmlDoc.Save("UpdateList.xml"); // 保存文件 } catch (Exception ex) { MsgDvUtil.ShowError("错误信息" + ex.Message); } return; } MsgDvUtil.ShowTips("UpdateFiles目录中无更新文件!"); } private void BtnUpload() { try { Control.CheckForIllegalCrossThreadCalls = false; Thread tmp = new Thread(new ThreadStart(upLoadFile)); tmp.Start(); } catch (SocketException ex) { MsgDvUtil.ShowWarning("上传文件失败:连接服务器失败,无法连接服务器。"); } } #region 文件上传功能 delegate void doProcessBar(ProgressODoom.ProgressBarEx pbar, int sender); delegate void doProcessLabel(Label label, string sender); public void DoneProcessBar(ProgressODoom.ProgressBarEx pbar, int sender) { if (pbar.InvokeRequired) { doProcessBar mydelegate = new doProcessBar(DoneProcessBar); pbar.Invoke(mydelegate, new object[] { pbar, sender }); } else { currentValve = sender; progressBar.Value = currentValve; } } public void BeforProcessBar(ProgressODoom.ProgressBarEx pbar, int sender) { if (pbar.InvokeRequired) { doProcessBar mydelegate = new doProcessBar(BeforProcessBar); pbar.Invoke(mydelegate, new object[] { pbar, sender }); } else { int size = int.Parse(sender.ToString()); currentValve = 0; maxValve = size; pbar.Visible = true; pbar.Maximum = size; } } public void DoneProcessLabel(Label label, string sender) { if (label.InvokeRequired) { doProcessLabel mydelegate = new doProcessLabel(DoneProcessLabel); label.Invoke(mydelegate, new object[] { label, sender }); } else { lblFileContent.Text = sender; } } private string FormatByteSize(int value) { if (value < 1024) { return value + "B"; } else if (value < 1048576) { return ((value * 1.0) / 1024).ToString(".##") + "KB"; } else if (value < 1073741824) { return ((value * 1.0) / 1048576).ToString(".##") + "MB"; } else { return ((value * 1.0) / 1073741824).ToString(".##") + "GB"; } } private string FormatKByteSize(int value) { if (value < 1024) { return ((value * 1.0)).ToString(".##") + "KB"; } else if (value < 1048576) { return ((value * 1.0) / 1024).ToString(".##") + "MB"; } else if (value < 1073741824) { return ((value * 1.0) / 1048576).ToString(".##") + "GB"; } else { return ((value * 1.0) / 1073741824).ToString(".##") + "TB"; } } private void upLoadFile() { try { if (!string.IsNullOrEmpty(txtLocalFilePath.Text)) { UploadCommon.BeforeUpLoad += BeforeFileUpLoad; UploadCommon.AfterUpLoad += AfterFileUpLoad; UploadCommon.DoUpLoad += doFileUpLoad; UploadCommon.ErrorUpLoad += errorFileUpLoad; UploadCommon c = new UploadCommon(); //-------------- if (lstFileList.Items.Count > 0) { int j = 0; string count = lstFileList.CheckedItems.Count.ToString(); for (int i = 0; i < lstFileList.Items.Count; i++) { if (lstFileList.Items[i].Checked) { j++; string fileName = Path.GetFileName(lstFileList.Items[i].Tag.ToString()).Trim(); c.UpLoadFile(txtServerIp.Text.Trim(), int.Parse(txtUPort.Text.Trim()), txtLocalFilePath.Text.Trim(), fileName); lstFileList.Items[i].Checked = false; } else { continue; } } MsgDvUtil.ShowTips("文件上传成功!"); } //--------------- //c.UpLoadFile(txtServerFileName.Text, int.Parse(txtUPort.Text), txtLocalFilePath.Text); } else { MsgDvUtil.ShowWarning("上传文件失败:该文件不存在"); } } catch (Exception e) { MsgDvUtil.ShowError("上传文件失败错误原因:" + e.ToString() + "。"); } } public void errorFileUpLoad(object sender) { MsgDvUtil.ShowError("上传文件出现错误:" + sender.ToString()); } public void BeforeFileUpLoad(object sender) { int size = int.Parse(sender.ToString()); BeforProcessBar(progressBar, size); string msg = "开始上传," + FormatKByteSize(currentValve) + "/" + FormatKByteSize(maxValve); DoneProcessLabel(lblFileContent, msg); } public void doFileUpLoad(object sender) { int size = int.Parse(sender.ToString()); DoneProcessBar(progressBar, size); string msg = "上传中," + FormatKByteSize(currentValve) + "/" + FormatKByteSize(maxValve); DoneProcessLabel(lblFileContent, msg); } public void AfterFileUpLoad(object sender) { int size = int.Parse(sender.ToString()); AfterProcessBar(progressBar, size); string msg = "上传已完成," + FormatKByteSize(currentValve) + "/" + FormatKByteSize(maxValve); DoneProcessLabel(lblFileContent, msg); } public void AfterProcessBar(ProgressODoom.ProgressBarEx pbar, int sender) { if (pbar.InvokeRequired) { doProcessBar mydelegate = new doProcessBar(AfterProcessBar); pbar.Invoke(mydelegate, new object[] { pbar, sender }); } else { currentValve = 0; progressBar.Visible = false; } } #endregion private void TmFile_Tick(object sender, EventArgs e) { lblFileContent.Text = FormatByteSize(currentValve) + "/" + FormatByteSize(maxValve); } } }