泰頂項(xiàng)目管理軟件(全功能開源版) v2025.04
253.3MB / 04-05
DBCHM beta數(shù)據(jù)庫文檔生成工具 v1.9.0.1
29.3MB / 08-16
eCRM(E客CRM)客戶關(guān)系管理系統(tǒng) v1.0.16
9.3MB / 04-13
C# 繪制隨機(jī)驗(yàn)證碼開發(fā)實(shí)例
0.11MB / 07-15
Util6MIS(優(yōu)六企服系統(tǒng)_附CMS插件及模板) v5.0 源碼版
28.2MB / 03-23
C#實(shí)現(xiàn)插件式開發(fā)源碼
0.09MB / 09-26
C#實(shí)現(xiàn)報警收集系統(tǒng)源碼
0.91MB / 07-31
C# 文字轉(zhuǎn)語音源碼
0.14MB / 07-28
基于C#語言開發(fā)文件上傳、后綴名稱判別功能
20KB / 07-26
C#圖片去背景示例源碼
113KB / 07-24
-
c# 網(wǎng)絡(luò)通信實(shí)現(xiàn)自動下載文件并進(jìn)行解壓縮開發(fā)實(shí)例 C#源碼 / 3.11MB
-
C#將時間戳與日期格式相互轉(zhuǎn)換的小工具 C#源碼 / 0.05MB
-
C#冒泡排序算法開發(fā)實(shí)例 C#源碼 / 0.13MB
-
c#調(diào)用bat文件開發(fā)實(shí)例 C#源碼 / 0.03MB
-
C#的layui風(fēng)格界面開發(fā)實(shí)例 C#源碼 / 15.16MB
-
C# 繪制隨機(jī)驗(yàn)證碼開發(fā)實(shí)例 C#源碼 / 0.11MB
-
c# 文本搜索器開發(fā)實(shí)例 C#源碼 / 0.05MB
-
-
駕培云智通(HDHDSS)駕校管理系統(tǒng) v1.0 C#源碼 / 47.6MB
-
Masuit.Tools v2025.4.4 C#源碼 / 359KB
詳情介紹
c# 網(wǎng)絡(luò)通信實(shí)現(xiàn)自動下載文件并進(jìn)行解壓縮,核心代碼如下所示:
using System; using System.Collections.Generic; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; namespace Server_Download { public partial class Form1 : Form { public Form1() { InitializeComponent(); Encoding getIniFileEncoding = GetIniFileEncoding(Environment.CurrentDirectory "\\Config.ini"); if (getIniFileEncoding != Encoding.Unicode) { string text = File.ReadAllText(Environment.CurrentDirectory "\\Config.ini", getIniFileEncoding); File.WriteAllText(Environment.CurrentDirectory "\\Config.ini", text, Encoding.Unicode); } StringBuilder Side_ = new StringBuilder(1024); GetPrivateProfileString("Config", "Side", "1", Side_, 1024, Environment.CurrentDirectory "\\Config.ini"); Side = Side_.ToString(); StringBuilder Update_time_ = new StringBuilder(1024); GetPrivateProfileString("Config", "Update_time", "1", Update_time_, 1024, Environment.CurrentDirectory "\\Config.ini"); Update_time = Update_time_.ToString(); StringBuilder SET_PORT_ = new StringBuilder(1024); GetPrivateProfileString("Server", "SET_PORT", "9988", SET_PORT_, 1024, Environment.CurrentDirectory "\\Config.ini"); SET_PORT = SET_PORT_.ToString(); StringBuilder Client_IP_ = new StringBuilder(1024); GetPrivateProfileString("Client", "Server_IP", "127.0.0.1", Client_IP_, 1024, Environment.CurrentDirectory "\\Config.ini"); Server_IP = Client_IP_.ToString(); StringBuilder Client_PORT_ = new StringBuilder(1024); GetPrivateProfileString("Client", "Server_PORT", "9988", Client_PORT_, 1024, Environment.CurrentDirectory "\\Config.ini"); Server_PORT = Client_PORT_.ToString(); StringBuilder Copy_Enabled_ = new StringBuilder(255); GetPrivateProfileString("Client", "Copy_Enabled", "0", Copy_Enabled_, 1024, Environment.CurrentDirectory "\\Config.ini"); Copy_Enabled = Copy_Enabled_.ToString(); StringBuilder Copy_Path_ = new StringBuilder(255); GetPrivateProfileString("Client", "Copy_Path", "", Copy_Path_, 1024, Environment.CurrentDirectory "\\Config.ini"); Copy_Path = Copy_Path_.ToString(); StringBuilder Paste_Path_ = new StringBuilder(255); GetPrivateProfileString("Client", "Paste_Path", "", Paste_Path_, 1024, Environment.CurrentDirectory "\\Config.ini"); Paste_Path = Paste_Path_.ToString(); StringBuilder File_Name_ = new StringBuilder(255); GetPrivateProfileString("Client", "File_Name", "", File_Name_, 1024, Environment.CurrentDirectory "\\Config.ini"); File_Name = File_Name_.ToString(); StringBuilder Save_Path_ = new StringBuilder(255); GetPrivateProfileString("Client", "Save_Path", Environment.CurrentDirectory, Save_Path_, 1024, Environment.CurrentDirectory "\\Config.ini"); if (Save_Path_.ToString() == "") { Save_Path = Environment.CurrentDirectory; } else { Save_Path = Save_Path_.ToString(); } for (int i=1;i<100 ;i ) { StringBuilder name = new StringBuilder(255); GetPrivateProfileString("Process", "name" i, "", name, 1024, Environment.CurrentDirectory "\\Config.ini"); if (name.ToString() != "") { jc_name.Add(name.ToString()); } else { break; } } } protected override void DefWndProc(ref System.Windows.Forms.Message m) { //string message; //richTextBox1.AppendText(ax "\r\n"); switch (m.Msg) {// case WM_SINFO://處理消息 richTextBox1.SelectionStart = richTextBox1.TextLength; // Scrolls the contents of the control to the current caret position. richTextBox1.ScrollToCaret(); //Caret意思:脫字符號;插入符號; (^) break; case WM_SINFO1://處理消息 richTextBox1.AppendText(System.DateTime.Now.ToString(("yyyy-MM-dd hh:mm:ss:fff") ": ")); richTextBox1.SelectionColor = Color.Black; richTextBox1.AppendText(Marshal.PtrToStringAnsi(m.LParam) "\r\n"); richTextBox1.SelectionStart = richTextBox1.TextLength; richTextBox1.ScrollToCaret(); break; case WM_SINFO2: //message = string.Format("收到從應(yīng)用程序發(fā)出的消息!參數(shù)為:{0}, {1}", m.WParam, m.LParam); richTextBox1.AppendText(System.DateTime.Now.ToString(("yyyy-MM-dd hh:mm:ss:fff") ": ")); richTextBox1.SelectionColor = Color.Green; richTextBox1.AppendText(Marshal.PtrToStringAnsi(m.LParam) "\r\n"); richTextBox1.SelectionStart = richTextBox1.TextLength; richTextBox1.ScrollToCaret(); break; case WM_SINFO3://處理消息 richTextBox1.AppendText(System.DateTime.Now.ToString(("yyyy-MM-dd hh:mm:ss:fff") ": ")); richTextBox1.SelectionColor = Color.Red; richTextBox1.AppendText(Marshal.PtrToStringAnsi(m.LParam) "\r\n"); richTextBox1.SelectionStart = richTextBox1.TextLength; richTextBox1.ScrollToCaret(); break; default: base.DefWndProc(ref m); break; } } public static Encoding GetIniFileEncoding(string filePath) { Encoding encoding = Encoding.Default; using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { // 獲取文件流中的字節(jié)序列 byte[] buffer = new byte[fs.Length]; fs.Read(buffer, 0, buffer.Length); // 檢測字節(jié)序列的編碼格式 if (buffer[0] == 0xEF && buffer[1] == 0xBB && buffer[2] == 0xBF) { encoding = Encoding.UTF8; } else if (buffer[0] == 0xFE && buffer[1] == 0xFF) { encoding = Encoding.BigEndianUnicode; } else if (buffer[0] == 0xFF && buffer[1] == 0xFE) { encoding = Encoding.Unicode; } else { // 如果沒有檢測到BOM,則使用默認(rèn)編碼格式 encoding = Encoding.Default; } } return encoding; } [DllImport("User32.dll", EntryPoint = "SendMessage")] private static extern int Informtion_SendMessage(IntPtr hWnd, int msg, uint wParam, IntPtr lParam); public const int USER = 0x0400; public const int WM_SINFO1 = USER 101; public const int WM_SINFO2 = USER 102; public const int WM_SINFO3 = USER 103; public const int WM_SINFO = USER 104; public const int WM_LOG = USER 105; public const int WM_DGV1 = USER 106; IntPtr handle = IntPtr.Zero; public void new_Show_Informtion(string Text, int Result_information) { if (Result_information == 3) { // timer1.Stop(); Informtion_SendMessage(handle, WM_SINFO3, 0, Marshal.StringToHGlobalAnsi(Text)); } else if (Result_information == 2) { // timer1.Stop(); Informtion_SendMessage(handle, WM_SINFO2, 0, Marshal.StringToHGlobalAnsi(Text)); } else if (Result_information == 1) { Informtion_SendMessage(handle, WM_SINFO1, 0, Marshal.StringToHGlobalAnsi(Text)); } } #region 服務(wù)端 static Dictionary<string, Socket> clientConnectionItems = new Dictionary<string, Socket> { }; // 創(chuàng)建一個和客戶端通信的套接字 static Socket socket_Server = null; /// <summary> /// 服務(wù)器監(jiān)聽 /// </summary> public void Server_Monitor(int Port) { //定義一個套接字用于監(jiān)聽客戶端發(fā)來的消息,包含三個參數(shù)(IP4尋址協(xié)議,流式連接,Tcp協(xié)議) socket_Server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //將IP地址和端口號綁定到網(wǎng)絡(luò)節(jié)點(diǎn)point上 IPEndPoint point = new IPEndPoint(IPAddress.Any, Port); //MessageBox.Show(IPAddress.Any.ToString()); //監(jiān)聽綁定的網(wǎng)絡(luò)節(jié)點(diǎn) socket_Server.Bind(point); //將套接字的監(jiān)聽隊(duì)列長度限制為50 socket_Server.Listen(50); //負(fù)責(zé)監(jiān)聽客戶端的線程:創(chuàng)建一個監(jiān)聽線程 Thread threadwatch = new Thread(watchconnecting); //將窗體線程設(shè)置為與后臺同步,隨著主線程結(jié)束而結(jié)束 threadwatch.IsBackground = true; //啟動線程 threadwatch.Start(); new_Show_Informtion("Start listening...", 1); } /// <summary> /// 服務(wù)器監(jiān)聽事件 /// </summary> void watchconnecting() { try { Socket connection = null; //持續(xù)不斷監(jiān)聽客戶端發(fā)來的請求 while (true) { try { connection = socket_Server.Accept(); } catch (Exception ex) { new_Show_Informtion(ex.Message, 3); break; } //獲取客戶端的IP和端口號 IPAddress clientIP = (connection.RemoteEndPoint as IPEndPoint).Address; int clientPort = (connection.RemoteEndPoint as IPEndPoint).Port; //讓客戶顯示"連接成功的"的信息 string sendmsg = "Successfully connected to the server!\r\n" "Local IP:" clientIP ",Local Port:" clientPort.ToString() "?" Update_time; byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg); //實(shí)際發(fā)送的字節(jié)數(shù)組比實(shí)際輸入的長度多1,用于存取標(biāo)識符 //標(biāo)識符添加在位置為0的地方 byte[] newBuffer = new byte[arrSendMsg.Length 1]; newBuffer[0] = 0; Buffer.BlockCopy(arrSendMsg, 0, newBuffer, 1, arrSendMsg.Length); connection.Send(newBuffer); //客戶端網(wǎng)絡(luò)結(jié)點(diǎn)號 string remoteEndPoint = connection.RemoteEndPoint.ToString(); //顯示與客戶端連接情況 new_Show_Informtion("Successfully established connection with client " remoteEndPoint "!\t\n", 1); //添加客戶端信息 clientConnectionItems.Add(remoteEndPoint, connection); IPEndPoint netpoint = connection.RemoteEndPoint as IPEndPoint; //創(chuàng)建一個通信線程 ParameterizedThreadStart pts = new ParameterizedThreadStart(ServerRec); Thread thread = new Thread(pts); //設(shè)置為后臺線程,隨著主線程退出而退出 thread.IsBackground = true; //啟動線程 thread.Start(connection); } } catch (Exception EX) { new_Show_Informtion("Error:" EX.Message , 3); } } /// <summary> /// 單條連接 /// </summary> /// <param name="obj"></param> private void ServerRec(object obj) { try { string recStr = null; Socket socketServer = obj as Socket; long fileLength = 0; while (true) { int firstRcv = 0; byte[] buffer = new byte[8 * 1024]; try { if (socketServer != null) firstRcv = socketServer.Receive(buffer); if (firstRcv > 0)//大于0,說明有東西傳過來 { if (buffer[0] == 0)//0對應(yīng)文字信息 { recStr = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1); //對接收的路徑進(jìn)行打包發(fā)送 //new_Show_Informtion("客戶端_" socketServer.RemoteEndPoint ":" recStr, 1); new_Show_Informtion("Client_" socketServer.RemoteEndPoint ":" recStr, 2); string[] value = new string[2] { socketServer.RemoteEndPoint.ToString(), recStr.ToString() }; ParameterizedThreadStart pts = new ParameterizedThreadStart(SendFile_); Thread thread_server_r = new Thread(pts); //設(shè)置為后臺線程,隨著主線程退出而退出 thread_server_r.IsBackground = true; //啟動線程 thread_server_r.Start(value); } } } catch (Exception ex) { clientConnectionItems.Remove(socketServer.RemoteEndPoint.ToString()); new_Show_Informtion("Client Count:" clientConnectionItems.Count, 3); new_Show_Informtion("System abnormality:" ex.Message, 3); break; } } } catch (Exception ex) { new_Show_Informtion("Error:" ex.Message, 3); } } public void SendFile_(object obj) { string[] value = (string[])obj; try { new_Show_Informtion("Send file for " value[0], 1); string SendFile_path = Environment.CurrentDirectory "\\" value[1].ToString(); if (CompressZipFile_ok.Contains(Path.GetFileNameWithoutExtension(SendFile_path))) { new_Show_Informtion("Waiting for compression!" value[0], 1); for (; ; ) { Application.DoEvents(); if (!CompressZipFile_ok.Contains(Path.GetFileNameWithoutExtension(SendFile_path))) { break; } Delay(500); } new_Show_Informtion("Compression completed!" value[0], 1); } if (!File.Exists(SendFile_path)) { if (!Directory.Exists(Path.GetDirectoryName(SendFile_path) "\\" Path.GetFileNameWithoutExtension(SendFile_path))) { SendStr("Error:The server did not find the file.", 3, value[0]); } else { new_Show_Informtion("Compressed file [" Path.GetDirectoryName(SendFile_path) "\\" Path.GetFileNameWithoutExtension(SendFile_path) "] " value[0], 1); CompressZipFile_ok.Add(Path.GetFileNameWithoutExtension(SendFile_path)); if (!compressedFile(Path.GetDirectoryName(SendFile_path) "\\" Path.GetFileNameWithoutExtension(SendFile_path), SendFile_path)) { SendStr("Error:Server compression failed.", 3, value[0]); } //Compress(Path.GetDirectoryName(path) "\\" Path.GetFileNameWithoutExtension(path), path); } } new_Show_Informtion("file name:" value[1], 1); new_Show_Informtion("ip:" value[0], 1); SendFile(SendFile_path, value[1], value[0]); } catch (Exception ex) { SendStr("Error:" ex.Message,3,value[0]); new_Show_Informtion("Error:" ex.Message, 3); } } #endregion #region 發(fā)送 /// <summary> /// 發(fā)送 /// </summary> /// <param name="SendStr">內(nèi)容</param> /// <param name="symbol"></param> /// <param name="IP">地址</param> private void SendStr(string SendStr, byte symbol, string IP) { try { Socket socketclientparalhy; //用UTF8能接受文字信息 byte[] buffer = Encoding.UTF8.GetBytes(SendStr); //實(shí)際發(fā)送的字節(jié)數(shù)組比實(shí)際輸入的長度多1,用于存取標(biāo)識符 byte[] newBuffer = new byte[buffer.Length 1]; //標(biāo)識符添加在位置為0的地方 newBuffer[0] = symbol; Buffer.BlockCopy(buffer, 0, newBuffer, 1, buffer.Length); clientConnectionItems.TryGetValue(IP, out socketclientparalhy); //; new_Show_Informtion(Encoding.UTF8.GetString(newBuffer, 1, newBuffer.Length - 1), 2); socketclientparalhy.Send(newBuffer); new_Show_Informtion(SendStr, 1); } catch (Exception exx) { new_Show_Informtion("An error occurred:" exx.Message, 3); } } private void SendFile(string fileFullPath, string fileName, string IP) { Socket socketclientparalhy; if (!File.Exists(fileFullPath)) { new_Show_Informtion("file does not exist!" IP, 3); SendStr("file does not exist!", 3, IP); return; } //發(fā)送文件前,將文件名和長度發(fā)過去 long fileLength = new FileInfo(fileFullPath).Length; string totalMsg = string.Format("{0}-{1}", fileName, fileLength); SendStr(totalMsg, 2, IP); Delay(2000); byte[] buffer = new byte[8 * 1024]; using (FileStream fs = new FileStream(fileFullPath, FileMode.Open, FileAccess.Read)) { int readLength = 0; bool firstRead = true; long sentFileLength = 0; while ((readLength = fs.Read(buffer, 0, buffer.Length)) > 0 && sentFileLength < fileLength) { sentFileLength = readLength; //第一次發(fā)送的字節(jié)流上加個前綴1 if (firstRead) { byte[] firstBuffer = new byte[readLength 1]; //標(biāo)記1,代表為文件 firstBuffer[0] = 1; Buffer.BlockCopy(buffer, 0, firstBuffer, 1, readLength); clientConnectionItems.TryGetValue(IP, out socketclientparalhy); socketclientparalhy.Send(firstBuffer, 0, readLength 1, SocketFlags.None); firstRead = false; continue; } clientConnectionItems.TryGetValue(IP, out socketclientparalhy); socketclientparalhy.Send(buffer, 0, readLength, SocketFlags.None); } fs.Close(); } new_Show_Informtion("Sent file:" fileName " to " IP " OK. ", 1); } #endregion bool khd_xc = true; #region 客戶端 Thread thread_client = null; Socket socket_client = null; public void Client(string IP,int Port) { //定義一個套接字監(jiān)聽 socket_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //獲取文本框中的IP地址 IPAddress address = IPAddress.Parse(IP.ToString());//127.0.0.1 //將獲取的IP地址和端口號綁定在網(wǎng)絡(luò)節(jié)點(diǎn)上 IPEndPoint point = new IPEndPoint(address, Port); try { //客戶端套接字連接到網(wǎng)絡(luò)節(jié)點(diǎn)上,用的是Connect socket_client.Connect(point); new_Show_Informtion("Connected to server " point "\r\n", 1); } catch (Exception esx) { Debug.WriteLine("connection failed.\r\n"); new_Show_Informtion("connection failed:" esx.Message "\r\n", 3); err ; return; } khd_xc = false; thread_client = new Thread(RecMsg); thread_client.IsBackground = true; thread_client.Start(); for (; ; ) { Application.DoEvents(); if (khd_xc) { break; } Delay(100); } } int err = 0; /// <summary> /// 客戶端監(jiān)聽事件 /// </summary> [DllImport("kernel32.dll")] static extern bool WritePrivateProfileString(string section, string key, string value, string filePath); string[] rt = new string[2]; private void RecMsg() { long fileLength = 0; string recStr = null; while (true) { try { int firstRcv = 0; byte[] buffer = new byte[8 * 1024]; if (socket_client != null) firstRcv = socket_client.Receive(buffer); if (firstRcv > 0) { if (buffer[0] == 0) { recStr = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1); new_Show_Informtion("Server:" recStr "\r\n", 2); rt = recStr.Split('?'); if (rt.Length >= 2 && rt[1] == Update_time) { new_Show_Informtion("No update required", 1); string zippath = Save_Path "\\" File_Name; //Delay(800); if (Directory.Exists(Path.GetDirectoryName(zippath) "\\" Path.GetFileNameWithoutExtension(zippath))) { System.Diagnostics.Process.Start("explorer.exe", Path.GetDirectoryName(zippath) "\\" Path.GetFileNameWithoutExtension(zippath)); //System.Diagnostics.Process.Start(Path.GetDirectoryName(zippath) "\\" Path.GetFileNameWithoutExtension(zippath)); } else { new_Show_Informtion("Open failed!", 3); } Delay(800); khd_xc = true; return; } string yjj_path = Path.GetDirectoryName(Save_Path "\\" File_Name) "\\" Path.GetFileNameWithoutExtension(Save_Path "\\" File_Name); new_Show_Informtion("Start deleting files[" yjj_path "]", 1); bool del = false; if (Directory.Exists(Path.GetDirectoryName(Save_Path "\\" File_Name) "\\" Path.GetFileNameWithoutExtension(Save_Path "\\" File_Name))) { //MessageBox.Show(Path.GetDirectoryName(Save_Path "\\" File_Name) "\\" Path.GetFileNameWithoutExtension(Save_Path "\\" File_Name)); del = deleteF(Path.GetDirectoryName(Save_Path "\\" File_Name) "\\" Path.GetFileNameWithoutExtension(Save_Path "\\" File_Name)); } else { del = true; } if (File.Exists(Save_Path "\\" recStr)) { File.Delete(Save_Path "\\" recStr); } if (del && !Directory.Exists(yjj_path)) { ClientSend(File_Name, 0);//? new_Show_Informtion("Start waiting for the server to send files.", 1); } else { new_Show_Informtion("File deletion failed:Please confirm if there are any background processes occupying it!", 3); err ; } } if (buffer[0] == 3) { recStr = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1); new_Show_Informtion("Server:" recStr "\r\n", 3); err ; } if (buffer[0] == 1) { this.Invoke((EventHandler)(delegate { progressBar1.Minimum = 0; progressBar1.Maximum = 100; })); if (!Directory.Exists(Save_Path)) { Directory.CreateDirectory(Save_Path); } string savePath = Save_Path "\\" recStr; int rec = 0; long recFileLength = 0; bool firstWrite = true; new_Show_Informtion("Start receiving files!", 1); using (FileStream fs = new FileStream(savePath, FileMode.Create, FileAccess.Write)) { while (recFileLength < fileLength) { this.Invoke((EventHandler)(delegate { progressBar1.Value = (int)((((float)recFileLength / (float)fileLength) * 100) 1); label2.Text = progressBar1.Value "%"; })); Application.DoEvents(); if (firstWrite) { fs.Write(buffer, 1, firstRcv - 1); fs.Flush(); recFileLength = firstRcv - 1; firstWrite = false; } else { rec = socket_client.Receive(buffer); fs.Write(buffer, 0, rec); fs.Flush(); recFileLength = rec; } Application.DoEvents(); } fs.Close(); this.Invoke((EventHandler)(delegate { progressBar1.Value = (int)((((float)recFileLength / (float)fileLength) * 100) ); label2.Text = progressBar1.Value "%"; })); } new_Show_Informtion("Receiving completed!", 1); string fName = savePath.Substring(savePath.LastIndexOf("\\") 1); string fPath = savePath.Substring(0, savePath.LastIndexOf("\\")); new_Show_Informtion("You have successfully received files from the server:" "\r\n" fName " Save path as:" fPath "\r\n", 2); if (File.Exists(savePath)) { new_Show_Informtion("Start decompressing!", 1); Extract_pok_OK = false; //Thread t_e = new Thread(new ParameterizedThreadStart(Extract_pok_)); // 啟動線程,并傳入?yún)?shù) //t_e.Start(savePath); //t_e.IsBackground = true; Extract_pok_(savePath); for (; ; ) { Application.DoEvents(); if (Extract_pok_OK) { break; } Delay(100); } //Extract(savePath, Path.GetDirectoryName(savePath) "\\" Path.GetFileNameWithoutExtension(savePath)); //Decompression(Path.GetDirectoryName(savePath) "\\" Path.GetFileNameWithoutExtension(savePath), savePath); } //Delay(800); new_Show_Informtion("[" Path.GetDirectoryName(savePath) "\\" Path.GetFileNameWithoutExtension(savePath) "]OK", 1); if (Directory.Exists(Path.GetDirectoryName(savePath) "\\" Path.GetFileNameWithoutExtension(savePath))) { System.Diagnostics.Process.Start("explorer.exe", Path.GetDirectoryName(savePath) "\\" Path.GetFileNameWithoutExtension(savePath)); //System.Diagnostics.Process.Start(Path.GetDirectoryName(savePath) "\\" Path.GetFileNameWithoutExtension(savePath)); } else { new_Show_Informtion("Open failed!", 3); } Delay(800); break; } if (buffer[0] == 2) { string fileNameWithLength = Encoding.UTF8.GetString(buffer, 1, firstRcv - 1); new_Show_Informtion(fileNameWithLength, 1); recStr = fileNameWithLength.Split('-').First(); fileLength = Convert.ToInt64(fileNameWithLength.Split('-').Last()); new_Show_Informtion("Server:[" recStr "][" fileLength "]", 2); } } } catch (Exception ex) { new_Show_Informtion("An error occurred:" ex.Message, 3); err ; break; } } khd_xc = true; } Process process_JY; public void Extract_pok_(object STR) { try { string pathTo7z = Environment.CurrentDirectory @"\7-zip\7z.exe";// @"D:\MyRepository\WorkRepository\Production_Do not modify\TOOL\Server_Download\Server_Download\bin\x86\Debug\7-Zip\7z.exe"; // 7z.exe 文件路徑 string archivePath = Path.GetFullPath(STR.ToString());// @"D:\MyRepository\FTA.rar"; // 要解壓縮的文件路徑Path.GetFullPath(value.ToString()), Path.GetDirectoryName(value.ToString()) "\\" Path.GetFileNameWithoutExtension(value.ToString()) string destinationPath = Path.GetDirectoryName(STR.ToString()) "\\" Path.GetFileNameWithoutExtension(STR.ToString());// @"D:\MyRepository\FTA"; // 解壓縮的目標(biāo)路徑 //string[] val; ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = pathTo7z; processStartInfo.Arguments = string.Format("x \"{0}\" -o\"{1}\" -bsp1 -bso0 -bse1", archivePath, destinationPath); //"x -y \"" archivePath "\" -oextracted -bso1 -bsp0"; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.CreateNoWindow = true; process_JY = new Process(); process_JY.StartInfo = processStartInfo; // 訂閱輸出事件 process_JY.OutputDataReceived = (sender, e) => { // if (e.Data != null) { if (e.Data.IndexOf("-") > -1 && e.Data.IndexOf("%") > -1) { this.Invoke((EventHandler)(delegate { //progressBar1.Value = int.Parse(e.Data.Split('%')[0].ToString()); label3.Text = e.Data; })); Application.DoEvents(); if (progressBar2.Value != int.Parse(e.Data.Split('%')[0].ToString())) { //Console.WriteLine(">" e.Data.Split('%')[0]); this.Invoke((EventHandler)(delegate { progressBar2.Value = int.Parse(e.Data.Split('%')[0].ToString()); //label1.Text = (e.Data.Split('%')[0].ToString()) "%"; })); } } /*else { Console.WriteLine(e.Data); }*/ } }; process_JY.EnableRaisingEvents = true; process_JY.Exited = new EventHandler(pz_Exited); process_JY.Start(); process_JY.BeginOutputReadLine(); process_JY.WaitForExit(); } catch (Exception ex) { this.Invoke((EventHandler)(delegate { new_Show_Informtion(ex.Message, 3); })); err ; Extract_pok_OK = true; } } Process process_YS; public bool compressedFile(string sourceFile, string destinationFile) { try { if (sourceFile.ToString() != "" && Directory.Exists(sourceFile.ToString())) { string pathTo7z = Environment.CurrentDirectory @"\7-zip\7z.exe"; ProcessStartInfo processStartInfo = new ProcessStartInfo(); processStartInfo.FileName = pathTo7z; processStartInfo.Arguments = string.Format("a \"{0}\" \"{1}\" -bsp1 -bso0 -bse1", destinationFile, sourceFile);//-bsp1 -bso0 -bse1 //"x -y \"" archivePath "\" -oextracted -bso1 -bsp0"; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.CreateNoWindow = true; process_YS = new Process(); process_YS.StartInfo = processStartInfo; // 訂閱輸出事件 process_YS.OutputDataReceived = (sender, e) => { //Console.WriteLine(e.Data); this.Invoke((EventHandler)(delegate { new_Show_Informtion("[" destinationFile "]" e.Data, 1); })); }; process_YS.EnableRaisingEvents = true; process_YS.Exited = new EventHandler(YS_Exited); process_YS.Start(); process_YS.BeginOutputReadLine(); process_YS.WaitForExit(); new_Show_Informtion("DeCompress file[" destinationFile "] OK!", 2); CompressZipFile_ok.Remove(Path.GetFileNameWithoutExtension(destinationFile)); return true; } else { new_Show_Informtion("DeCompress File[" destinationFile "] Error!", 3); CompressZipFile_ok.Remove(Path.GetFileNameWithoutExtension(destinationFile)); return false; } } catch (Exception ex) { this.Invoke((EventHandler)(delegate { new_Show_Informtion(ex.Message, 3); })); CompressZipFile_ok.Remove(Path.GetFileNameWithoutExtension(destinationFile)); return false; } } private void YS_Exited(object sender, EventArgs e) { this.Invoke((EventHandler)(delegate { new_Show_Informtion("Compression End!", 1); })); } bool Extract_pok_OK = true; private void pz_Exited(object sender, EventArgs e) { this.Invoke((EventHandler)(delegate { new_Show_Informtion("Decompression completed!", 2); progressBar2.Value = 100; label3.Text = "100%"; })); Extract_pok_OK = true; } private void ClientSend(string SendStr, byte symbol) { byte[] buffer = Encoding.UTF8.GetBytes(SendStr); byte[] newBuffer = new byte[buffer.Length 1]; newBuffer[0] = symbol; Buffer.BlockCopy(buffer, 0, newBuffer, 1, buffer.Length); socket_client.Send(newBuffer); new_Show_Informtion(SendStr, 1); } #endregion string Save_Path = ""; string SET_PORT = "9988"; string Server_IP = "127.0.0.1"; string Server_PORT = "9988"; string File_Name = ""; string Side = "1"; string Update_time = "20130101"; string Copy_Enabled = "0"; string Copy_Path = ""; string Paste_Path = ""; private void button1_Click(object sender, EventArgs e) { Server_Monitor(int.Parse(SET_PORT)); button1.Enabled = false; } [DllImport("kernel32")] private static extern int GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, int nSize, string lpFileName); private void Form1_Load(object sender, EventArgs e) { handle = this.Handle; string executablePath = System.Reflection.Assembly.GetExecutingAssembly().Location; string executableName = Path.GetFileNameWithoutExtension(executablePath); //Path.GetFileName(); this.Text= executableName; if (Side.ToUpper() == "0") { GB_Client.Visible = false; GB_Server.Visible = true; new_Show_Informtion(SET_PORT, 1); } else if (Side.ToUpper() == "1") { this.ControlBox = false; GB_Client.Visible = true; GB_Server.Visible = false; new_Show_Informtion(Server_IP, 1); new_Show_Informtion(Server_PORT, 1); new_Show_Informtion(File_Name, 1); new_Show_Informtion(Save_Path, 1); new_Show_Informtion(jc_name.Count.ToString(), 1); } new_Show_Informtion("Config OK", 1); } private void btnConnection_Click(object sender, EventArgs e) { btnConnection.Enabled = false; progressBar1.Value = 0; label2.Text = ""; progressBar2.Value = 0; label3.Text = ""; Delay(100); new_Show_Informtion("Start updating!", 1); Application.DoEvents(); err = 0; Client(Server_IP, int.Parse(Server_PORT)); if (Copy_Enabled == "1") { try { File.Copy(Copy_Path, Paste_Path, true); new_Show_Informtion("Successfully replaced file!", 1); } catch (Exception ex) { new_Show_Informtion(ex.Message, 3); } }else { new_Show_Informtion("No need to replace!", 1); } Delay(1000); btnConnection.Enabled = true; if (err == 0) { WritePrivateProfileString("Config", "Update_time", rt[1], Environment.CurrentDirectory "\\Config.ini"); new_Show_Informtion("Close.", 1); StopProcess(System.Diagnostics.Process.GetCurrentProcess().ProcessName); } else { new_Show_Informtion(err.ToString(), 1); this.ControlBox = true; } } public static void StopProcess(string processName) { try { System.Diagnostics.Process[] ps = System.Diagnostics.Process.GetProcessesByName(processName); foreach (System.Diagnostics.Process p in ps) { p.Kill(); } } catch (Exception ex) { throw ex; } } List<string> CompressZipFile_ok = new List<string>(); public bool deleteF(string val) { try { //delete_file(val); delete_file_(); new_Show_Informtion("Process shutdown OK", 2); new_Show_Informtion("Deleting file, please wait...", 1); DeleteFolder(val); new_Show_Informtion("File deleted successfully.", 2); return true; } catch (Exception ex) { new_Show_Informtion(ex.Message, 3); return false; } } public const int OF_READWRITE = 2; public const int OF_SHARE_DENY_NONE = 0x40; public readonly IntPtr HFILE_ERROR = new IntPtr(-1); public void DeleteFolder(object dir) { if (Directory.Exists(dir.ToString())) //如果存在這個文件夾刪除之 { foreach (string d in Directory.GetFileSystemEntries(dir.ToString())) { if (File.Exists(d)) { File.SetAttributes(d, FileAttributes.Normal); File.Delete(d); //直接刪除其中的文件 /*for (int i=0;;i ) { if (!File.Exists(d)) { break; } try { File.Delete(d); } catch { delete_file(Path.GetDirectoryName(d)); Delay(100); } if (i > 10) { File.Delete(d); } }*/ } else { DeleteFolder(d); } //Application.DoEvents(); } try { Directory.Delete(dir.ToString(), true); } catch (Exception ee) { new_Show_Informtion(ee.Message, 3); } } } public void deleteUploadOaFolder(string folderPath) { try { //去除文件夾和子文件的只讀屬性 //去除文件夾的只讀屬性 System.IO.DirectoryInfo fileInfo = new DirectoryInfo(folderPath); fileInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory; System.IO.File.SetAttributes(folderPath, System.IO.FileAttributes.Normal); //去除文件的只讀屬性 if (Directory.Exists(folderPath)) { foreach (string f in Directory.GetFileSystemEntries(folderPath)) { if (File.Exists(f)) //判斷文件夾是否還存在 { //如果有子文件刪除文件 try { File.Delete(f); } catch (Exception ex) { delete_file(f); File.Delete(f); } } else { //循環(huán)遞歸刪除子文件夾 deleteUploadOaFolder(f); } } //刪除空根文件夾。即傳來一個文件夾如:/upload/kahnFolder/,則最后將根文件夾kahnFolder也刪除掉 //Directory.Delete(folderPath); } } catch (Exception ex) // 異常處理 { Console.WriteLine(ex.Message.ToString()); // 異常信息 } } Process process_delF; List<string> uid = new List<string>(); List<string> jc_name = new List<string>(); public void delete_file(string fileName) { string handle_32_64 = ""; process_delF = new Process(); if (Environment.Is64BitOperatingSystem) { handle_32_64 = @"\handel\handle64.exe"; } else { handle_32_64 = @"\handel\handle.exe"; } //System.Diagnostics.Process p = new System.Diagnostics.Process(); //p.StartInfo = new System.Diagnostics.ProcessStartInfo(Environment.CurrentDirectory handle_32_64); //p.Start(); //p.WaitForExit(); process_delF.StartInfo.FileName = Environment.CurrentDirectory handle_32_64; process_delF.StartInfo.Arguments = string.Format("\"{0}\"", (fileName)); process_delF.StartInfo.UseShellExecute = false; process_delF.StartInfo.RedirectStandardOutput = true; process_delF.StartInfo.CreateNoWindow = true; process_delF.Start(); process_delF.WaitForExit(); string outputTool = process_delF.StandardOutput.ReadToEnd(); uid.Clear(); string matchPattern = @"(?<=\s pid:\s )\b(\d )\b(?=\s )"; //MessageBox.Show(outputTool); foreach (Match match in Regex.Matches(outputTool, matchPattern)) { //Process.GetProcessById(int.Parse(match.Value)).Kill(); //Process.GetProcessById(int.Parse(match.Value)).CloseMainWindow(); if (!uid.Contains(match.Value)) { Process pro = Process.GetProcessById(int.Parse(match.Value)); pro.Kill(); uid.Add(match.Value); } } } public void delete_file_() { var pro = Process.GetProcesses("."); //將進(jìn)程轉(zhuǎn)化為 集合,并且篩選加排序 var result = pro.OrderBy(p => p.ProcessName).Select(p => new { p.Id, p.ProcessName, p.MainWindowTitle }).ToList(); //int index = -1; result.ForEach((x) => { int index = jc_name.FindIndex(kjc => kjc.ToUpper().IndexOf(x.ProcessName.ToUpper())>-1); if (index>-1) { int id = Convert.ToInt32(x.Id); Process prox = Process.GetProcessById(id); prox.Kill(); } }); } [DllImport("kernel32.dll")] static extern uint GetTickCount(); public void Delay(uint ms) { uint start = GetTickCount(); while (GetTickCount() - start < ms) { Application.DoEvents(); } } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (Side.ToUpper() == "1"&&err==0) { e.Cancel = true; // 取消關(guān)閉操作 return; } if (process_JY != null && !process_JY.HasExited) { process_JY.Kill(); } if (process_YS != null && !process_YS.HasExited) { process_YS.Kill(); } if (process_delF != null && !process_delF.HasExited) { process_delF.Kill(); } //e.Cancel = true; StopProcess(System.Diagnostics.Process.GetCurrentProcess().ProcessName); //process_delF //System.Environment.Exit(0); } private void label1_Click(object sender, EventArgs e) { new_Show_Informtion(SET_PORT, 1); new_Show_Informtion(Server_IP, 1); new_Show_Informtion(Server_PORT, 1); new_Show_Informtion(File_Name, 1); new_Show_Informtion(Save_Path, 1); } private void Form1_Shown(object sender, EventArgs e) { if (Side.ToUpper() == "1") { btnConnection_Click(sender, e); } } private void Form1_Resize(object sender, EventArgs e) { if (Side.ToUpper() == "0") { if (this.WindowState == FormWindowState.Minimized) //如果窗體被最小化 { this.notifyIcon1.Visible = true; //顯示通知圖標(biāo) this.notifyIcon1.Text = this.Text; this.Visible = false; //使Form不在任務(wù)欄上顯示 } } } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { if (Side.ToUpper() == "0") { if (this.WindowState == FormWindowState.Minimized) //如果窗體被最小化 { this.Visible = true; this.notifyIcon1.Visible = false; } } } private void Form1_VisibleChanged(object sender, EventArgs e) { if (this.Visible) { //this.ShowInTaskbar = true;//使Form不在任務(wù)欄上顯示 this.WindowState = FormWindowState.Normal; } else { //this.ShowInTaskbar = false; this.WindowState = FormWindowState.Minimized; } } public void DeleteFolder_(object dir) { if (Directory.Exists(dir.ToString())) //如果存在這個文件夾刪除之 { foreach (string d in Directory.GetFileSystemEntries(dir.ToString())) { if (File.Exists(d)) { File.SetAttributes(d, FileAttributes.Normal); File.Delete(d); } else { DeleteFolder_(d); } //Application.DoEvents(); } try { Directory.Delete(dir.ToString(), true); } catch (Exception ee) { new_Show_Informtion(ee.Message, 3); } } } private void button2_Click(object sender, EventArgs e) { //MessageBox.Show(deleteF(@"D:\新建文件夾\update").ToString()); try { DeleteFolder_(@"D:\新建文件夾\update"); } catch (Exception ex) { new_Show_Informtion(ex.Message, 3); } /*string filePath = "C:\\test.txt"; // 設(shè)置文件屬性為FILE_FLAG_DELETE_ON_CLOSE IntPtr handle = CreateFile(filePath, FileAccess.ReadWrite, FileShare.ReadWrite, IntPtr.Zero, FileMode.Open, FileAttributes.Normal | FileAttributes.DeleteOnClose, IntPtr.Zero); if (handle != IntPtr.Zero && handle.ToInt32() != -1) { CloseHandle(handle); } else { // 文件無法打開,可能處于使用中狀態(tài),嘗試重試或報錯處理 }*/ } [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] static extern IntPtr CreateFile(string lpFileName, FileAccess dwDesiredAccess, FileShare dwShareMode, IntPtr lpSecurityAttributes, FileMode dwCreationDisposition, FileAttributes dwFlagsAndAttributes, IntPtr hTemplateFile); [DllImport("kernel32.dll", SetLastError = true)] static extern bool CloseHandle(IntPtr hObject); private void button2_Click_1(object sender, EventArgs e) { delete_file_(); } private void button2_Click_2(object sender, EventArgs e) { File.Copy(Copy_Path, Paste_Path, true); } private void button2_Click_3(object sender, EventArgs e) { Extract_pok_(@"C:\Users\86183\Desktop\Microsoft.NETFramework4.rar"); } } }
下載地址
人氣源碼
相關(guān)文章
-
泰頂項(xiàng)目管理軟件(全功能開源版) v2025.04
泰頂項(xiàng)目管理軟件[綜合平臺],始于2010年,具有強(qiáng)大的項(xiàng)目計(jì)劃和流程管控功能,上千用戶使用,模塊俱全,架構(gòu)靈活,成熟可靠,適用于多個行業(yè)的專業(yè)的項(xiàng)目管理軟件平臺...
-
DBCHM beta數(shù)據(jù)庫文檔生成工具 v1.9.0.1
DBCHM 是一款簡單、實(shí)用的數(shù)據(jù)庫文檔生成工具,該工具從最初支持chm文檔格式開始,通過開源,集思廣益,不斷改進(jìn),本文給大家介紹DBCHM beta數(shù)據(jù)庫文檔生成工具 v1.9.0.1 ...
-
eCRM(E客CRM)客戶關(guān)系管理系統(tǒng) v1.0.16
eCRM(E客CRM)是基于eFrameWork低代碼開發(fā)平臺搭建的客戶關(guān)系管理系統(tǒng)。其主要功能包括:系統(tǒng)管理、產(chǎn)品管理、產(chǎn)品分類、客戶管理、訂單管理、客戶回訪、通知公告、銷售計(jì)劃...
-
C# 繪制隨機(jī)驗(yàn)證碼開發(fā)實(shí)例
在C#中繪制驗(yàn)證碼通常涉及到生成一組隨機(jī)字符,然后將這些字符繪制到一個圖像上,下面給大家分享C# 繪制隨機(jī)驗(yàn)證碼的實(shí)例,感興趣的朋友下載體驗(yàn)吧...
-
Util6MIS(優(yōu)六企服系統(tǒng)_附CMS插件及模板) v5.0 源碼版
Util6MIS(優(yōu)六企服系統(tǒng))已集成多項(xiàng)插件系統(tǒng),其Util6 CMS、DMS、OAS、WXS 是在信息化管理系統(tǒng)框架(Util6MIS)基礎(chǔ)上開發(fā)的插件系統(tǒng),歡迎需要的朋友下載使用...
-
C#實(shí)現(xiàn)插件式開發(fā)源碼
今天給大家分享基于c#開發(fā)的插件式源碼,喜歡的朋友快來下載體驗(yàn)吧...
-
C#實(shí)現(xiàn)報警收集系統(tǒng)源碼
今天給大家分享的是一款基于C#實(shí)現(xiàn)報警收集系統(tǒng)源碼,非常不錯,喜歡的朋友快來下載體驗(yàn)吧...
-
C# 文字轉(zhuǎn)語音源碼
今天給大家分享的實(shí)例代碼是C# 文字轉(zhuǎn)語音源碼,喜歡的朋友快來下載體驗(yàn)吧...
-
基于C#語言開發(fā)文件上傳、后綴名稱判別功能
今天給大家分享基于c#語言開發(fā)的文件上傳、后綴名稱判別功能,喜歡的朋友快來下載使用吧...
-
C#圖片去背景示例源碼
今天給大家分享基于c#實(shí)現(xiàn)圖片去背景示例源碼,喜歡的朋友快來下載體驗(yàn)吧...
下載聲明
☉ 解壓密碼:www.dbjr.com.cn 就是本站主域名,希望大家看清楚,[ 分享碼的獲取方法 ]可以參考這篇文章
☉ 推薦使用 [ 迅雷 ] 下載,使用 [ WinRAR v5 ] 以上版本解壓本站軟件。
☉ 如果這個軟件總是不能下載的請?jiān)谠u論中留言,我們會盡快修復(fù),謝謝!
☉ 下載本站資源,如果服務(wù)器暫不能下載請過一段時間重試!或者多試試幾個下載地址
☉ 如果遇到什么問題,請?jiān)u論留言,我們定會解決問題,謝謝大家支持!
☉ 本站提供的一些商業(yè)軟件是供學(xué)習(xí)研究之用,如用于商業(yè)用途,請購買正版。
☉ 本站提供的c# 網(wǎng)絡(luò)通信實(shí)現(xiàn)自動下載文件并進(jìn)行解壓縮開發(fā)實(shí)例資源來源互聯(lián)網(wǎng),版權(quán)歸該下載資源的合法擁有者所有。