标签:position ica help console dir abs enc man ror
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Utilities; using System.Net.Http; using System.Net; using System.Net.Http.Headers; using System.Drawing; using System.IO.Compression; namespace Expander { public partial class OperationDataForm : Form { private string server = "http://localhost:5000"; public const int step = 2; public OperationDataForm() { InitializeComponent(); } private void FolderSelectBtn_Click(object sender, EventArgs e) {
// 初始化 文件上传 按钮 using (var fbd = new FolderBrowserDialog()) { var result = fbd.ShowDialog(); if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath)) { rootFolderTextBox.Text = fbd.SelectedPath; this.UploadFileBtn.Enabled = false; this.ProgressBarPanel.Visible = false; } } } private void CheckFileBtn_Click(object sender, EventArgs e) { //判断文件路径是否存在 string filePath = this.rootFolderTextBox.Text; FolderExsitStatus folderExistStatus = FileSystemUtilities.IsFileExsit(filePath); if (folderExistStatus.ToString() != "FolderExsit") { MessageBox.Show("file path is not exist"); } else { bool accessStatus = FileSystemUtilities.CheckAccessControl(filePath); if (!accessStatus) { MessageBox.Show("file path not access."); } else { InitLabelData(); // reset value this.CheckResultDataSet.Items.Clear(); this.CheckResultDataSet.Refresh(); UploadFileBtn.Enabled = false; UploadFileBtn.Refresh(); // 创建文件路径 string[] folderFilePathList = Directory.GetDirectories(filePath); this.CheckResultDataSet.BeginUpdate(); int successCount = 0; int failCount = 0; this.CountLabel.Text = "Count: " + folderFilePathList.Length.ToString(); this.CountLabel.Refresh(); foreach (string folderFilePath in folderFilePathList) { var checkRes = ValidatorUtilities.ValidateDataFolder(folderFilePath); ListViewItem lvi = new ListViewItem(); string resMessage = ""; string resStatus = ""; if (checkRes.Item2 == null) { resMessage = "OK"; resStatus = "Success"; lvi.ImageIndex = 1; successCount++; this.SuccessLabel.Text = "Success: " + successCount.ToString(); this.SuccessLabel.Refresh(); } else { resMessage = checkRes.Item2.ToString(); resStatus = "Fail"; lvi.ImageIndex = 0; failCount++; this.FailLabel.Text = "Fail: " + failCount.ToString(); this.FailLabel.Refresh(); } lvi.SubItems.Add(resStatus); lvi.SubItems.Add(folderFilePath.Split(‘\\‘)[folderFilePath.Split(‘\\‘).Length - 1]); lvi.SubItems.Add(resMessage); lvi.SubItems.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); this.CheckResultDataSet.Items.Add(lvi); } this.CheckResultDataSet.EndUpdate(); this.CheckResultDataSet.Sort(); this.CheckResultDataSet.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); // update load if (folderFilePathList.Length == successCount) { UploadFileBtn.Enabled = true; } } } } public void AutoSizeForm() { int width = this.Width; int height = this.Height; int splitterDistance = this.splitContainer1.SplitterDistance; int rightPanelHeight = this.splitContainer1.Panel2.Height; int rightPanelWidth = width - splitterDistance; this.CheckResultDataSet.Height = int.Parse((rightPanelHeight * 0.815).ToString().Split(‘.‘)[0]); this.CheckResultDataSet.Width = int.Parse((rightPanelWidth * 0.94).ToString().Split(‘.‘)[0]); this.ProgressBarPanel.Width = int.Parse((rightPanelWidth * 0.70).ToString().Split(‘.‘)[0]); this.myProgressBar2.Width = int.Parse((rightPanelWidth * 0.68).ToString().Split(‘.‘)[0]); this.CheckResultDataSet.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } private void OperationDataForm_Load(object sender, EventArgs e) { this.UploadFileBtn.Enabled = false; // init listview this.CheckResultDataSet.Columns.Add("", 45, HorizontalAlignment.Left); this.CheckResultDataSet.Columns.Add("Status", 80, HorizontalAlignment.Left); this.CheckResultDataSet.Columns.Add("Person Folder Name", 240, HorizontalAlignment.Left); this.CheckResultDataSet.Columns.Add("Message", 280, HorizontalAlignment.Left); this.CheckResultDataSet.Columns.Add("Update Time", 150, HorizontalAlignment.Left); InitLabelData(); AutoSizeForm(); this.CheckResultDataSet.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize); } private void UploadFileBtn_Click(object sender, EventArgs e) { string sourceFilePath = this.rootFolderTextBox.Text; // personId dir string[] PersonFilesArray = Directory.GetFileSystemEntries(sourceFilePath); this.ProgressBarPanel.Visible = true; this.ProgressBarInfo.Text = "Data uploading .."; // load progressBar this.myProgressBar2.Maximum = PersonFilesArray.Count(); this.myProgressBar2.Minimum = 0; this.myProgressBar2.Value = 0; this.ProgressBarInfo.Refresh(); this.CloseProgressBarPictureBox.Refresh(); this.ProgressBarPanel.Refresh(); // get taskId string taskId = GetTaskId(); // pack in memory and send int personNumIndex = 0; int arrSize = PersonFilesArray.Count() % step == 0 ? PersonFilesArray.Count() / step : PersonFilesArray.Count() / step + 1; int progressSep = int.Parse((100 / arrSize).ToString().Split(‘.‘)[0]); while (personNumIndex * step < PersonFilesArray.Count()) { List<string> sub = PersonFilesArray.Skip(personNumIndex * step).Take(step).ToList(); // generate zipData in memory byte[] memoryZipData = PackedFileZip(sub); // send http server var res = HttpClientPostUpload(memoryZipData, taskId, "result.zip"); if (res.Item1 == 0) { // upload success Console.WriteLine("taskId={0},updalod success and personIds={1} ", taskId, res.Item2); } else { // upload fail Console.WriteLine(string.Format("taskId={0}, updalod fail and errorMessage={1}", taskId, res.Item2)); } if (Math.Abs(personNumIndex * step - this.myProgressBar2.Maximum) < step) { this.myProgressBar2.Value = this.myProgressBar2.Maximum; } else { this.myProgressBar2.Value = personNumIndex * step + step; } personNumIndex++; this.myProgressBar2.Refresh(); } string accomplishUrl = server + "/accomplish?taskId=" + taskId; HttpWebResponse response = HttpHelper(accomplishUrl); if (response.StatusCode == HttpStatusCode.OK) { Console.WriteLine("taskId={0} success and transmission end"); } else { Console.WriteLine(string.Format("taskId={0} fail and statuCode is {1}", taskId, response.StatusDescription)); } // show close button this.CloseProgressBarPictureBox.Visible = true; } private void ListViewColumnClick(object sender, ColumnClickEventArgs e) { this.CheckResultDataSet.ListViewItemSorter = new ListViewItemComparer(); // Call the sort method to manually sort. this.CheckResultDataSet.Sort(); } private void ListViewMouseDoubleClick(object sender, MouseEventArgs e) { ListView listview = (ListView)sender; ListViewItem lstrow = listview.GetItemAt(e.X, e.Y); ListViewItem.ListViewSubItem lstcol = lstrow.GetSubItemAt(e.X, e.Y); string strText = lstcol.Text; try { Clipboard.SetDataObject(strText); MessageBox.Show("Copy successfully.", "提示", MessageBoxButtons.OK); } catch (Exception ex) { MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } public void InitLabelData() { // init label this.CountLabel.Text = "Count: 0 "; this.SuccessLabel.Text = "Success: 0"; this.FailLabel.Text = "Fail: 0"; this.CountLabel.Refresh(); this.SuccessLabel.Refresh(); this.FailLabel.Refresh(); } private void FormSizeChanged(object sender, EventArgs e) { AutoSizeForm(); } public string GetTaskId() { var urlstring = server + "/assign"; HttpWebResponse response2 = HttpHelper(urlstring); if (response2.StatusCode == HttpStatusCode.OK) { StreamReader sr2 = new StreamReader(response2.GetResponseStream(), Encoding.UTF8); string result = sr2.ReadToEnd(); return result; } else { return "test"; } } public HttpWebResponse HttpHelper(string url, string method = "POST") { // string param = (obj);参数 byte[] bs = Encoding.Default.GetBytes(""); HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url); req.Method = method; req.ContentType = "application/json"; req.ContentLength = bs.Length; using (Stream reqStream = req.GetRequestStream()) { reqStream.Write(bs, 0, bs.Length); reqStream.Close(); HttpWebResponse response2 = (HttpWebResponse)req.GetResponse(); return response2; } } public (int, string) HttpClientPostUpload(byte[] bmpBytes, string taskId, string fileName) { using (var client = new HttpClient()) { List<ByteArrayContent> list = new List<ByteArrayContent>(); var dataContent = new ByteArrayContent(Encoding.UTF8.GetBytes(taskId)); dataContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")//内容处置标头 { Name = "taskId" }; list.Add(dataContent); var fileContent = new ByteArrayContent(bmpBytes);//填充图片字节 fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data") { Name = "uploadFile", FileName = fileName }; list.Add(fileContent); using (var content = new MultipartFormDataContent()) { Action<List<ByteArrayContent>> act = (dataContents) => {//声明一个委托,该委托的作用就是将ByteArrayContent集合加入到MultipartFormDataContent中 foreach (var byteArrayContent in dataContents) { content.Add(byteArrayContent); } }; act(list);//执行act try { var result = client.PostAsync(server+"/submit", content).Result;//post请求 return (0, result.Content.ReadAsStringAsync().Result); } catch (Exception ex) { return (1, ex.Message); } } } } public byte[] FileStreamToByte(string filePath) { string path = filePath; FileStream fs = new FileStream(path, FileMode.Open); //获取文件大小 long size = fs.Length; byte[] array = new byte[size]; //将文件读到byte数组中 fs.Read(array, 0, array.Length); fs.Close(); return array; } public byte[] StreamToBytes(Stream stream) { byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 设置当前流的位置为流的开始 stream.Seek(0, SeekOrigin.Begin); return bytes; } public byte[] PackedFileZip(List<string> personPaths) { using (Stream memoryStream = new MemoryStream()) { using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true)) { foreach (string path in personPaths) { string personId = Path.GetFileName(path); foreach (string file in Directory.EnumerateFiles(path)) { ZipArchiveEntry entry = archive.CreateEntry($"{personId}/{Path.GetFileName(file)}"); using (Stream entryStream = entry.Open()) using (Stream fileStream = File.OpenRead(file)) { fileStream.CopyTo(entryStream); } } } } memoryStream.Seek(0, SeekOrigin.Begin); return StreamToBytes(memoryStream); } } private List<List<string>> GroupListBySize(string[] list, int size) { List<List<string>> listArr = new List<List<string>>(); int arrSize = list.Count() % size == 0 ? list.Count() / size : list.Count() / size + 1; for (int i = 0; i < arrSize; i++) { List<string> sub = new List<string>(); for (int j = i * size; j <= size * (i + 1) - 1; j++) { if (j <= list.Count() - 1) { sub.Add(list[j]); } } listArr.Add(sub); } return listArr; } private void CloseProgressBar_Click(object sender, EventArgs e) { this.ProgressBarPanel.Visible = false; this.CloseProgressBarPictureBox.Visible = false; this.myProgressBar2.Value = 0; this.myProgressBar2.Refresh(); this.CloseProgressBarPictureBox.Refresh(); } private void CloseProgressBarPictureBox_MouseHover(object sender, EventArgs e) { this.CloseProgressBarPictureBox.Cursor = Cursors.Hand; } private void splitContainer1_SplitterMoved(object sender, SplitterEventArgs e) { int formWidth = this.Width; int rightPanelWidth = formWidth - this.splitContainer1.SplitterDistance; this.CheckResultDataSet.Width = int.Parse((rightPanelWidth * 0.94).ToString().Split(‘.‘)[0]); this.ProgressBarPanel.Width = int.Parse((rightPanelWidth * 0.70).ToString().Split(‘.‘)[0]); this.myProgressBar2.Width = int.Parse((rightPanelWidth * 0.68).ToString().Split(‘.‘)[0]); } private void CheckInfoPanel_Paint(object sender, PaintEventArgs e) { //Panel pan = (Panel)sender; //float width = (float)0.5; //Pen pen = new Pen(SystemColors.ControlDark, width); //pen.DashStyle = DashStyle.Solid; //e.Graphics.DrawLine(pen, 0, 0, 0, pan.Height - 0); //e.Graphics.DrawLine(pen, 0, 0, pan.Width - 0, 0); //e.Graphics.DrawLine(pen, pan.Width - 1, pan.Height - 1, 0, pan.Height - 1); //e.Graphics.DrawLine(pen, pan.Width - 1, pan.Height - 1, pan.Width - 1, 0); } } public class ListViewItemComparer : System.Collections.IComparer { private int col=1; public int Compare(object x, object y) { int returnVal = -1; returnVal = String.Compare(((ListViewItem)x).SubItems[col].Text, ((System.Windows.Forms.ListViewItem)y).SubItems[col].Text); return returnVal; } } public class MyProgressBar : ProgressBar { //public int Value = 0; public MyProgressBar() { SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true); //Value = 1; } public new int Value { get; set; } protected override void OnPaint(PaintEventArgs e) { //base.OnPaint(e); Rectangle rect = ClientRectangle; Graphics g = e.Graphics; ProgressBarRenderer.DrawHorizontalBar(g, rect); rect.Inflate(-3, -3); if (Value > 0) { var clip = new Rectangle(rect.X, rect.Y, (int)((float)(this.Value) / Maximum * rect.Width), rect.Height); ProgressBarRenderer.DrawHorizontalChunks(g, clip); } string text = string.Format("{0}/{1}", Value , Maximum); using (var font = new Font(FontFamily.GenericSerif, 18)) { SizeF sz = g.MeasureString(text, font); var location = new PointF(rect.Width / 2 - sz.Width / 2, rect.Height / 2 - sz.Height / 2 + 5); g.DrawString(text, font, Brushes.Black, location); } } } }
代码功能包括:
1:
c# 在内存打包zip 多个文件 上传服务器 MemoryStream ZipArchiveMode
标签:position ica help console dir abs enc man ror
原文地址:https://www.cnblogs.com/zknublx/p/13097771.html