c# 檔案傳輸

來源:互聯網
上載者:User

今天終於把檔案傳輸問題給研究明白了,特發此代碼用來協助正在學習的人們。

send :

Code
  string path = "E:\\c#\\convey_file\\convey_file\\Form1.cs";                //要傳輸的檔案
           TcpClient client = new TcpClient();
           client.Connect(IPAddress.Parse("192.168.0.52"),9999);
            FileStream file = new FileStream(path,FileMode.Open,FileAccess.Read);  //注意與receive的filestream的區別
            BinaryReader binaryreader = new BinaryReader(file);
            byte[] b = new byte[4098];
            int data;
            Console.WriteLine("正在傳送檔案");
            while ((data = binaryreader.Read(b, 0, 4098)) != 0)                 //這個注意是將檔案寫成流的形式
            {
                client.Client.Send(b,data,SocketFlags.None);           //傳送檔案流到目標機器
            }
           client.Client.Shutdown(SocketShutdown.Both);
           binaryreader.Close();
           file.Close();

Code

receive:

Code
 private Socket s;
        TcpListener tl;
        public void lis()
        {
            string path = "d:\\1.cs";                 //要傳入檔案的路徑
            tl = new TcpListener(9999);
            tl.Start();
            Console.WriteLine("等待接受");
            s = tl.AcceptSocket();
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);   //注意這個的屬性和send端有所不同
            BinaryWriter binarywrite = new BinaryWriter(fs);
            int count;
            byte[] b = new byte[4098];
            while ((count = s.Receive(b, 4098, SocketFlags.None)) != 0)             //這個是接受檔案流
            {
                binarywrite.Write(b,0,count);                          //將接收的流用寫成檔案
            }
            binarywrite.Close();
            fs.Close();
            s.Close();
            tl.Stop();
            Console.WriteLine("檔案傳輸完畢");

 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.