C#文件传送相关代码详解

开发 后端
这里将对C#文件传送的相关代码进行解释,用到一个C#文件传送的实例来做范例。希望本文能对大家了解文件传送机制有所帮助。
C#文件传送使用较为频繁的场景,是即时聊天工具中的文件传输。比如点对点方面的传送。在一般情况下,C#文件传送都要对通信端口,连接的控制,异常的控制等做好准备。

这个C#文件传送程序是借鉴TcpFileTransferDemo项目的来的。C#文件传送源码很少,还有改进的地方就是可以用多线程进行大文件传送。

  1. using System;  
  2. using System.Drawing;  
  3. using System.Collections;  
  4. using System.ComponentModel;  
  5. using System.Windows.Forms;  
  6.  
  7. using System.Data;  
  8. using System.IO;  
  9. using System.Net;  
  10. using System.Net.Sockets;  
  11. using System.Threading;  
  12.  
  13.  
  14. namespace CSharpData  
  15. {  
  16.  ///   
  17.  /// SaveFileForm 的摘要说明。  
  18.  /// 
  19.  
  20.  public class SaveFileForm : System.Windows.Forms.Form  
  21.  {  
  22.   private System.Windows.Forms.Panel panel1;  
  23.   private System.Windows.Forms.TextBox textBox2;  
  24.   private System.Windows.Forms.Label label2;  
  25.   private System.Windows.Forms.TextBox textBox1;  
  26.   private System.Windows.Forms.Label label1;  
  27.   private System.Windows.Forms.Button button4;  
  28.   private System.Windows.Forms.Button button3;  
  29.   private System.Windows.Forms.Button button2;  
  30.   private System.Windows.Forms.Button button1;  
  31.   private System.Windows.Forms.StatusBar statusBar1;  
  32.   ///   
  33.   /// 必需的设计器变量。  
  34.   /// 
  35.  
  36.   private System.ComponentModel.Container components = null;  
  37.  
  38.     
  39.  
  40.   public SaveFileForm()  
  41.   {  
  42.    //  
  43.    // Windows 窗体设计器支持所必需的  
  44.    //  
  45.    InitializeComponent();  
  46.  
  47.    setStatusDelegate = new SetStatusDelegate(SetStatus);  
  48.    getSaveFileDelegate = new GetSaveFileDelegate(GetSaveFile);  
  49.    //  
  50.    // TODO: 在 InitializeComponent 调用后添加任何构造函数代码  
  51.    //  
  52.   }  
  53.  
  54.   ///   
  55.   /// 清理所有正在使用的资源。  
  56.   /// 
  57.  
  58.   protected override void Dispose( bool disposing )  
  59.   {  
  60.    if( disposing )  
  61.    {  
  62.     if(components != null)  
  63.     {  
  64.      components.Dispose();  
  65.     }  
  66.    }  
  67.    base.Dispose( disposing );  
  68.   }  
  69.  
  70.   #region Windows 窗体设计器生成的代码  
  71.   ///   
  72.   /// 设计器支持所需的方法 - 不要使用代码编辑器修改  
  73.   /// 此方法的内容。  
  74.   /// 
  75.  
  76.   private void InitializeComponent()  
  77.   {  
  78.    this.panel1 = new System.Windows.Forms.Panel();  
  79.    this.textBox2 = new System.Windows.Forms.TextBox();  
  80.    this.label2 = new System.Windows.Forms.Label();  
  81.    this.textBox1 = new System.Windows.Forms.TextBox();  
  82.    this.label1 = new System.Windows.Forms.Label();  
  83.    this.button4 = new System.Windows.Forms.Button();  
  84.    this.button3 = new System.Windows.Forms.Button();  
  85.    this.button2 = new System.Windows.Forms.Button();  
  86.    this.button1 = new System.Windows.Forms.Button();  
  87.    this.statusBar1 = new System.Windows.Forms.StatusBar();  
  88.    this.panel1.SuspendLayout();  
  89.    this.SuspendLayout();  
  90.    //   
  91.    // panel1  
  92.    //   
  93.    this.panel1.Controls.Add(this.textBox2);  
  94.    this.panel1.Controls.Add(this.label2);  
  95.    this.panel1.Controls.Add(this.textBox1);  
  96.    this.panel1.Controls.Add(this.label1);  
  97.    this.panel1.Controls.Add(this.button4);  
  98.    this.panel1.Controls.Add(this.button3);  
  99.    this.panel1.Controls.Add(this.button2);  
  100.    this.panel1.Controls.Add(this.button1);  
  101.    this.panel1.Location = new System.Drawing.Point(8, 16);  
  102.    this.panel1.Name = "panel1";  
  103.    this.panel1.Size = new System.Drawing.Size(272, 152);  
  104.    this.panel1.TabIndex = 0;  
  105.    //   
  106.    // textBox2  
  107.    //   
  108.    this.textBox2.Location = new System.Drawing.Point(96, 64);  
  109.    this.textBox2.Name = "textBox2";  
  110.    this.textBox2.TabIndex = 15;  
  111.    this.textBox2.Text = "800";  
  112.    //   
  113.    // label2  
  114.    //   
  115.    this.label2.Location = new System.Drawing.Point(8, 72);  
  116.    this.label2.Name = "label2";  
  117.    this.label2.Size = new System.Drawing.Size(80, 16);  
  118.    this.label2.TabIndex = 14;  
  119.    this.label2.Text = "通信端口";  
  120.    //   
  121.    // textBox1  
  122.    //   
  123.    this.textBox1.Location = new System.Drawing.Point(96, 24);  
  124.    this.textBox1.Name = "textBox1";  
  125.    this.textBox1.TabIndex = 13;  
  126.    this.textBox1.Text = "192.168.1.250";  
  127.    //   
  128.    // label1  
  129.    //   
  130.    this.label1.Location = new System.Drawing.Point(8, 32);  
  131.    this.label1.Name = "label1";  
  132.    this.label1.Size = new System.Drawing.Size(80, 16);  
  133.    this.label1.TabIndex = 12;  
  134.    this.label1.Text = "IP地址";  
  135.    //   
  136.    // button4  
  137.    //   
  138.    this.button4.Location = new System.Drawing.Point(160, 104);  
  139.    this.button4.Name = "button4";  
  140.    this.button4.Size = new System.Drawing.Size(64, 23);  
  141.    this.button4.TabIndex = 11;  
  142.    this.button4.Text = "接收文件";  
  143.    this.button4.Click += new System.EventHandler(this.button4_Click);  
  144.    //   
  145.    // button3  
  146.    //   
  147.    this.button3.Location = new System.Drawing.Point(56, 104);  
  148.    this.button3.Name = "button3";  
  149.    this.button3.Size = new System.Drawing.Size(64, 23);  
  150.    this.button3.TabIndex = 10;  
  151.    this.button3.Text = "发送文件";  
  152.    this.button3.Click += new System.EventHandler(this.button3_Click);  
  153.    //   
  154.    // button2  
  155.    //   
  156.    this.button2.Location = new System.Drawing.Point(200, 64);  
  157.    this.button2.Name = "button2";  
  158.    this.button2.Size = new System.Drawing.Size(64, 23);  
  159.    this.button2.TabIndex = 9;  
  160.    this.button2.Text = "停止监听";  
  161.    this.button2.Click += new System.EventHandler(this.button2_Click);  
  162.    //   
  163.    // button1  
  164.    //   
  165.    this.button1.Location = new System.Drawing.Point(200, 24);  
  166.    this.button1.Name = "button1";  
  167.    this.button1.Size = new System.Drawing.Size(64, 23);  
  168.    this.button1.TabIndex = 8;  
  169.    this.button1.Text = "开始监听";  
  170.    this.button1.Click += new System.EventHandler(this.button1_Click);  
  171.    //   
  172.    // statusBar1  
  173.    //   
  174.    this.statusBar1.Location = new System.Drawing.Point(0, 191);  
  175.    this.statusBar1.Name = "statusBar1";  
  176.    this.statusBar1.Size = new System.Drawing.Size(292, 22);  
  177.    this.statusBar1.TabIndex = 1;  
  178.    this.statusBar1.Text = "statusBar1";  
  179.    //   
  180.    // SaveFileForm  
  181.    //   
  182.    this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);  
  183.    this.ClientSize = new System.Drawing.Size(292, 213);  
  184.    this.Controls.Add(this.statusBar1);  
  185.    this.Controls.Add(this.panel1);  
  186.    this.Name = "SaveFileForm";  
  187.    this.Text = "局域网内接收文件";  
  188.    this.panel1.ResumeLayout(false);  
  189.    this.ResumeLayout(false);  
  190.  
  191.   }  
  192.   #endregion  
  193.  
  194.   private void button1_Click(object sender, System.EventArgs e)  
  195.   {  
  196.    port = 0;  
  197.    try 
  198.    {  
  199.     port = int.Parse(textBox2.Text);  
  200.     if (port < 1 || port > 65535) throw new ArgumentOutOfRangeException();  
  201.    }  
  202.    catch 
  203.    {  
  204.     MessageBox.Show("请输入有效的端口号。");  
  205.     textBox2.Focus();  
  206.     textBox2.SelectAll();  
  207.     return;  
  208.    }  
  209.    button1.Enabled = false;  
  210.    button2.Enabled = true;  
  211.    worker = new Thread(new ThreadStart(Start));  
  212.    worker.IsBackground = true;  
  213.    worker.Start();  
  214.   }  
  215.  
  216.   private void button2_Click(object sender, System.EventArgs e)  
  217.   {  
  218.    try { worker.Abort(); }  
  219.    catch {}  
  220.   }  
  221.  
  222.   private void button3_Click(object sender, System.EventArgs e)  
  223.   {  
  224.     
  225.   }  
  226.  
  227.   private void button4_Click(object sender, System.EventArgs e)  
  228.   {  
  229.     
  230.   }  
  231.  
  232.   #region 程序逻辑  
  233.   private Thread worker;  
  234.   private int port;  
  235.  
  236.   private void Start()  
  237.   {  
  238.    try // 捕获线程中止异常  
  239.    {  
  240.     SetStatus("开始侦听端口");  
  241.     TcpListener tcpListener = new TcpListener(IPAddress.Any, port);  
  242.     try // 捕获开始侦听时出现的错误,例如端口已被占用  
  243.     {  
  244.      tcpListener.Start();  
  245.     }  
  246.     catch (Exception e)  
  247.     {  
  248.      SetStatus("侦听端口出错:" + e.Message);  
  249.      InvokeCancel();  
  250.      return;  
  251.     }  
  252.     try // 确保停止侦听  
  253.     {  
  254.      SetStatus("等待传入连接中");  
  255.      while (true// 一直循环,直到线程被中止。但每次只处理一个连接  
  256.      {  
  257.       // 没有等待传入的连接就一直等待。不使用异步模型以提高程序可读性  
  258.       while (!tcpListener.Pending())  
  259.        Thread.Sleep(100);  
  260.  
  261.       TcpClient tcpClient = tcpListener.AcceptTcpClient();  
  262.       tcpClient.NoDelay = true;  
  263.       tcpClient.ReceiveTimeout = 30000;  
  264.       BinaryReader reader = new BinaryReader(tcpClient.GetStream());  
  265.  
  266.       try // 捕获文件传输中途出现的错误,并确保关闭连接  
  267.       {  
  268.        string filename = reader.ReadString();  
  269.        long total = reader.ReadInt64();  
  270.        SetStatus("收到文件传输请求,文件名 " + filename +  
  271.         ",大小 " + total.ToString() + " 字节");  
  272.  
  273.        string saveAs = GetSaveFile(filename);  
  274.        if (saveAs == null)  
  275.        {  
  276.         SetStatus("操作已取消。等待下一连接中");  
  277.         // finally 段会帮忙关闭连接  
  278.        }  
  279.        else 
  280.        {  
  281.         SetStatus("接收文件中");  
  282.         FileStream fs = File.Create(saveAs);  
  283.         try 
  284.         {  
  285.          byte[] buffer = new byte[8192];  
  286.          int len;  
  287.          while (total > 0)  
  288.          {  
  289.           len = reader.Read(buffer, 0, 8192);  
  290.           if (len == 0)  
  291.            throw new IOException("发送方中止了连接");  
  292.           fs.Write(buffer, 0, len);  
  293.           SetStatus("接收文件中 - 剩余 " +  
  294.            (total -= len).ToString() + " 字节");  
  295.          }  
  296.          SetStatus("文件已保存至 " + saveAs +  
  297.           "。等待下一连接中");  
  298.         }  
  299.         finally 
  300.         {  
  301.          fs.Close();  
  302.         }  
  303.        }  
  304.       }  
  305.       catch (Exception e)  
  306.       {  
  307.        SetStatus("文件传输中途出错:" + e.Message);  
  308.        InvokeCancel();  
  309.       }  
  310.       finally 
  311.       {  
  312.        try { reader.Close(); }  
  313.        catch {}  
  314.        try { tcpClient.Close(); }  
  315.        catch {}  
  316.       }  
  317.      }  
  318.     }  
  319.     finally 
  320.     {  
  321.      tcpListener.Stop();  
  322.     }  
  323.    }  
  324.    catch (ThreadAbortException)  
  325.    {  
  326.     SetStatus("用户中断");  
  327.     InvokeCancel();  
  328.    }  
  329.    finally 
  330.    {  
  331.     worker = null;  
  332.    }  
  333.   }  
  334.   #endregion  
  335.  
  336.   #region 线程安全UI操作代码  
  337.   private delegate void SetStatusDelegate(string status);  
  338.   private SetStatusDelegate setStatusDelegate; // 赋值在构造函数里  
  339.  
  340.   private void SetStatus(string status)  
  341.   {  
  342.    if (InvokeRequired)  
  343.     Invoke(setStatusDelegate, new object[] { status });  
  344.    else 
  345.     statusBar1.Text = status;  
  346.   }  
  347.  
  348.   private void InvokeCancel()  
  349.   {  
  350.    if (InvokeRequired)  
  351.     Invoke(new MethodInvoker(InvokeCancel));  
  352.    else 
  353.    {  
  354.     button2.Enabled = false;  
  355.     button1.Enabled = true;  
  356.    }  
  357.   }  
  358.  
  359.   private delegate string GetSaveFileDelegate(string filename);  
  360.   private GetSaveFileDelegate getSaveFileDelegate; //  
  361.     
  362.   private string GetSaveFile(string filename)  
  363.   {  
  364.    if (InvokeRequired)  
  365.     return (string)Invoke(getSaveFileDelegate, new object[] { filename });  
  366.    else 
  367.    {  
  368.     //打开要发送的文件  
  369.     SaveFileDialog sfd = new SaveFileDialog();  
  370.     sfd.FileName = filename;  
  371.     if (sfd.ShowDialog(this) == DialogResult.OK)  
  372.      return sfd.FileName;  
  373.     else 
  374.      return null;  
  375.    }  
  376.   }  
  377.   #endregion  
  378.  }  

【编辑推荐】

  1. C# this关键字详解
  2. C#调用析构方法详解
  3. C#释放托管资源简单描述
  4. C#单路代理简单分析
  5. C#文法产生式概述
责任编辑:彭凡 来源: CSDN
相关推荐

2009-04-03 10:25:32

C#XML扩展代码

2009-09-02 17:12:06

C#关机代码

2009-09-01 10:37:51

C#项目代码C#代码规范

2009-09-07 06:48:13

C#透明窗体

2009-08-12 14:13:51

C#读写Excel文件

2009-08-13 09:34:55

C#读写ini文件

2009-12-24 09:16:11

C#泛型

2009-09-02 14:00:34

C#文件处理

2009-08-18 17:05:08

C#操作xml文件

2009-08-13 09:58:55

C#读取配置文件

2009-08-28 14:34:47

C# Global.a

2009-09-01 16:49:56

C#文件上传下载

2009-09-01 11:25:08

C#读取Word文件

2009-08-14 13:52:18

C#判断数据类型

2009-08-20 16:50:14

C# 16进制转换10

2009-09-02 18:28:00

C#鼠标位置

2009-08-18 13:35:06

C#枚举文件

2009-09-07 18:41:18

2009-08-27 15:53:30

C#中using wo

2024-04-03 00:10:24

C#System数据
点赞
收藏

51CTO技术栈公众号