Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize File transfer in C #

2025-01-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article is to share with you about how C # implements file transfer. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

The scenario where C# file transfer is frequently used is the file transfer in the live chat tool. Such as peer-to-peer transmission. In general, C# file transfer should be prepared for communication port, connection control, abnormal control and so on.

This C# file transfer program is borrowed from the TcpFileTransferDemo project. C # file transfer source code is very little, there is an improvement is that you can use multi-threading for large file transfer.

Summary description of using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Data; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading; namespace CSharpData {/ SaveFileForm. / public class SaveFileForm: System.Windows.Forms.Form {private System.Windows.Forms.Panel panel1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button4; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button1 Private System.Windows.Forms.StatusBar statusBar1; / required designer variables. / private System.ComponentModel.Container components = null; public SaveFileForm () {/ Windows forms designer support required / / InitializeComponent (); setStatusDelegate = new SetStatusDelegate (SetStatus); getSaveFileDelegate = new GetSaveFileDelegate (GetSaveFile) / TODO: add any constructor code / /} / to clean up all resources in use after the InitializeComponent call. / / protected override void Dispose (bool disposing) {if (disposing) {if (components! = null) {components.Dispose ();}} base.Dispose (disposing) The code generated by the region Windows forms designer supports the required methods-do not use the code editor to modify the contents of this method. / / private void InitializeComponent () {this.panel1 = new System.Windows.Forms.Panel (); this.textBox2 = new System.Windows.Forms.TextBox (); this.label2 = new System.Windows.Forms.Label (); this.textBox1 = new System.Windows.Forms.TextBox (); this.label1 = new System.Windows.Forms.Label (); this.button4 = new System.Windows.Forms.Button (); this.button3 = new System.Windows.Forms.Button () This.button2 = new System.Windows.Forms.Button (); this.button1 = new System.Windows.Forms.Button (); this.statusBar1 = new System.Windows.Forms.StatusBar (); this.panel1.SuspendLayout (); this.SuspendLayout (); / panel1 / / this.panel1.Controls.Add (this.textBox2); this.panel1.Controls.Add (this.label2); this.panel1.Controls.Add (this.textBox1) This.panel1.Controls.Add (this.label1); this.panel1.Controls.Add (this.button4); this.panel1.Controls.Add (this.button3); this.panel1.Controls.Add (this.button2); this.panel1.Controls.Add (this.button1); this.panel1.Location = new System.Drawing.Point (8,16); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size (272152) This.panel1.TabIndex = 0; / textBox2 / / this.textBox2.Location = new System.Drawing.Point (96,64); this.textBox2.Name = "textBox2"; this.textBox2.TabIndex = 15; this.textBox2.Text = "800,800"; / label2 / / this.label2.Location = new System.Drawing.Point (8,72); this.label2.Name = "label2" This.label2.Size = new System.Drawing.Size (80,16); this.label2.TabIndex = 14; this.label2.Text = "Communication Port"; / textBox1 / / this.textBox1.Location = new System.Drawing.Point (96,24); this.textBox1.Name = "textBox1"; this.textBox1.TabIndex = 13; this.textBox1.Text = "192.168.1.250" / label1 / / this.label1.Location = new System.Drawing.Point (8,32); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size (80,16); this.label1.TabIndex = 12; this.label1.Text = "IP address"; / button4 / / this.button4.Location = new System.Drawing.Point (160104) This.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size (64,23); this.button4.TabIndex = 11; this.button4.Text = "receive files"; this.button4.Click + = new System.EventHandler (this.button4_Click); / button3 / / this.button3.Location = new System.Drawing.Point (56,104); this.button3.Name = "button3" This.button3.Size = new System.Drawing.Size (64,23); this.button3.TabIndex = 10; this.button3.Text = "send File"; this.button3.Click + = new System.EventHandler (this.button3_Click); / button2 / / this.button2.Location = new System.Drawing.Point (200,64); this.button2.Name = "button2" This.button2.Size = new System.Drawing.Size (64,23); this.button2.TabIndex = 9; this.button2.Text = "stop listening"; this.button2.Click + = new System.EventHandler (this.button2_Click); / button1 / / this.button1.Location = new System.Drawing.Point (200,24); this.button1.Name = "button1" This.button1.Size = new System.Drawing.Size (64,23); this.button1.TabIndex = 8; this.button1.Text = "start listening"; this.button1.Click + = new System.EventHandler (this.button1_Click); / statusBar1 / / this.statusBar1.Location = new System.Drawing.Point (0191); this.statusBar1.Name = "statusBar1" This.statusBar1.Size = new System.Drawing.Size (292,22); this.statusBar1.TabIndex = 1; this.statusBar1.Text = "statusBar1"; / SaveFileForm / / this.AutoScaleBaseSize = new System.Drawing.Size (6,14); this.ClientSize = new System.Drawing.Size (292,213); this.Controls.Add (this.statusBar1); this.Controls.Add (this.panel1); this.Name = "SaveFileForm" This.Text = "receive files in the local area network"; this.panel1.ResumeLayout (false); this.ResumeLayout (false);} # endregion private void button1_Click (object sender, System.EventArgs e) {port = 0; try {port = int.Parse (textBox2.Text); if (port)

< 1 || port >

65535) throw new ArgumentOutOfRangeException ();} catch {MessageBox.Show ("Please enter a valid port number") ; textBox2.Focus (); textBox2.SelectAll (); return;} button1.Enabled = false; button2.Enabled = true; worker = new Thread (new ThreadStart (Start)); worker.IsBackground = true; worker.Start ();} private void button2_Click (object sender, System.EventArgs e) {try {worker.Abort () } catch {}} private void button3_Click (object sender, System.EventArgs e) {} private void button4_Click (object sender, System.EventArgs e) {} # region program logic private Thread worker; private int port; private void Start () {try / / catch thread abort exception {SetStatus ("start listening port") TcpListener tcpListener = new TcpListener (IPAddress.Any, port); try / / captures errors that occur when listening, such as port occupied {tcpListener.Start ();} catch (Exception e) {SetStatus ("listening port error:" + e.Message); InvokeCancel (); return } try / / make sure to stop listening on {SetStatus ("waiting for incoming connection"); while (true) / / loops until the thread is aborted. But only one connection at a time {/ / has been waiting without waiting for incoming connections. Do not use an asynchronous model to improve program readability while (! tcpListener.Pending ()) Thread.Sleep (100); TcpClient tcpClient = tcpListener.AcceptTcpClient (); tcpClient.NoDelay = true; tcpClient.ReceiveTimeout = 30000; BinaryReader reader = new BinaryReader (tcpClient.GetStream ()) Try / / capture errors in the middle of a file transfer and make sure to close the connection {string filename = reader.ReadString (); long total = reader.ReadInt64 (); SetStatus ("received file transfer request, file name" + filename + ", size" + total.ToString () + "bytes"); string saveAs = GetSaveFile (filename) If (saveAs = = null) {SetStatus ("the operation has been cancelled. Waiting for the next connection "); / / the finally segment will help close the connection} else {SetStatus (" receiving files "); FileStream fs = File.Create (saveAs); try {byte [] buffer = new byte [8192]; int len While (total > 0) {len = reader.Read (buffer, 0, 8192); if (len = = 0) throw new IOException ("sender aborted the connection"); fs.Write (buffer, 0, len) SetStatus ("receive file-remaining" + (total-= len). ToString () + "bytes");} SetStatus ("File has been saved to" + saveAs + ". Waiting for next connection ");} finally {fs.Close ();} catch (Exception e) {SetStatus (" File transfer error: "+ e.Message); InvokeCancel ();} finally {try {reader.Close () } catch {} try {tcpClient.Close ();} catch {} finally {tcpListener.Stop ();}} catch (ThreadAbortException) {SetStatus ("user interrupt"); InvokeCancel ();} finally {worker = null } # endregion # region thread safe UI operation code private delegate void SetStatusDelegate (string status); private SetStatusDelegate setStatusDelegate; / / assignment in the constructor private void SetStatus (string status) {if (InvokeRequired) Invoke (setStatusDelegate, new object [] {status}); else statusBar1.Text = status;} private void InvokeCancel () {if (InvokeRequired) Invoke (new MethodInvoker (InvokeCancel)) Else {button2.Enabled = false; button1.Enabled = true;}} private delegate string GetSaveFileDelegate (string filename); private GetSaveFileDelegate getSaveFileDelegate; / / private string GetSaveFile (string filename) {if (InvokeRequired) return (string) Invoke (getSaveFileDelegate, new object [] {filename}); else {/ / Open the file SaveFileDialog sfd = new SaveFileDialog (); sfd.FileName = filename If (sfd.ShowDialog (this) = = DialogResult.OK) return sfd.FileName; else return null;}} # endregion}} Thank you for reading! This is the end of the article on "how to achieve file transfer in C#". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report