Thursday, 31 October 2013

Sending File from one computer to another using C#

     
In this article we are going to see how to send a file from one computer to another using TCP protocol.
now in this example i am taking my own laptop as Client and server, so IpAddress are same when you want to send to different mention the correct IpAddress and binding Port Number.

For Server Side Code 
C# :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace RServer
{
    public partial class Form1 : Form
    {

        public delegate void Add(String Message);

        Add mess;
        public void AddMessage(String Message)
        {
            listBox1.Items.Add(Message);
        }

        public Form1()
        {
            InitializeComponent();
            mess = new Add(AddMessage);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            System.Threading.ThreadPool.QueueUserWorkItem(StartTcpServer);
        }

        public  string GetIP()
        {
            string name = Dns.GetHostName();
            IPHostEntry entry= Dns.GetHostEntry(name);
            IPAddress[] addr = entry.AddressList;
            if (addr[1].ToString().Split('.').Length == 4)
            {
                return addr[1].ToString();
            }
            return addr[2].ToString();
        }

        public void Message(string data)
        {
            listBox1.BeginInvoke(mess, data);

        }

        public  void StartTcpServer(object state)
        {
            TcpListener filelistener = new TcpListener(IPAddress.Parse(GetIP()),8085);
            filelistener.Start();
            TcpClient client = filelistener.AcceptTcpClient();
            Message("Client connection accepted from :" + client.Client.RemoteEndPoint + ".");
            byte []buffer = new byte[1500];
            int bytesread = 1;

            StreamWriter writer = new StreamWriter("D:\\sample.rar");

            while (bytesread > 0)
            {
                bytesread= client.GetStream().Read(buffer, 0, buffer.Length);
                if (bytesread == 0)
                    break;
                writer.BaseStream.Write(buffer, 0, buffer.Length);
                Message(bytesread + " Received. ");
            }
            writer.Close();

        }
    }
}



For Client Side Code:
C# :

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Net.Sockets;
using System.Net;

namespace RServer
{
    public partial class Form3 : Form
    {
        public Form3()
        {
            InitializeComponent();
        }

        public string GetIP()
        {
            string name = Dns.GetHostName();
            IPHostEntry entry = Dns.GetHostEntry(name);
            IPAddress[] addr = entry.AddressList;
            if (addr[1].ToString().Split('.').Length == 4)
            {
                return addr[1].ToString();
            }
            return addr[2].ToString();
        }


        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                StreamReader sr = new StreamReader(textBox1.Text);

                TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(new IPEndPoint(IPAddress.Parse(GetIP()), 8085));

                byte[] buffer = new byte[1500];
                long bytesSent = 0;

                while (bytesSent < sr.BaseStream.Length)
                {
                    int bytesRead = sr.BaseStream.Read(buffer, 0, 1500);
                    tcpClient.GetStream().Write(buffer, 0, bytesRead);
                    Message(bytesRead + " bytes sent.");

                    bytesSent += bytesRead;
                }

                tcpClient.Close();

                Message("finished");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void Message(string data)
        {
            listBox1.Items.Add(data);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.ShowDialog();
            textBox1.Text = op.FileName;
        }

    }
}




Output :
Server


Client



I Hope from this article you can learn how to send file from computer to another.

19 comments:

  1. can u please forward me the code on my account
    pembu01@gmail.com
    It would be so great of u

    ReplyDelete
  2. it was so helpful sir for your codes it worked out and it's working

    ReplyDelete
  3. Hi pemboo00,

    You can take this code and make a winforms application by paste the code just change the namespace for the application.

    ReplyDelete
  4. i got this error "Only one usage of each socket address (protocol/network address/port) is normally permitted" how to rectify it

    ReplyDelete
  5. Check once whether the socket:port is already in use for some other application !! use this cmd

    netstat -a -b

    Which wil list all port in use and the application exe name

    ReplyDelete
  6. Hi sir, can u forward me the code, keith_dizon0529@yahoo.com to be my reference, it will be a great help, thanks

    ReplyDelete
    Replies
    1. Just copy paste the above code in ur application , it works well . . .Tested one

      Delete
  7. Sir, I have tried your code it sends a file but when i extract that file the file is corrupted.

    ReplyDelete
    Replies
    1. Hi,

      The Code works well, i didn't thing so file may be corrupt, because the data is transferring as byte by byte, so corrupt only possible in huge transfer in single send and receive data. Can you please catch the error along with stack trace and post here , then only i can debug the bug and able to give the solution.

      Delete
    2. The file size is 2.5 MB. At receiving side it shows size as either 3 MB or 90KB. Hence while doing unzip it gives error

      Delete
    3. Can you paste the code that you have written by using this code

      Delete
  8. Will this code also enable file sharing over the internet?

    ReplyDelete
  9. Access to the path 'C:\sample.rar' is denied.

    ReplyDelete
  10. This comment has been removed by the author.

    ReplyDelete
  11. This comment has been removed by the author.

    ReplyDelete
  12. Sir Raj Esh. Can you forward the code. Please i need to Review this code. Pls Sir Raj. This is my Gmail Acc. Melvinbarrios08@gmail.com Thanks Sir.

    ReplyDelete
  13. Chaitali Patil says true,
    D:\received file.rar: The archive is either in unknown format or damaged

    ReplyDelete
  14. very nice sharing keep up sharing your great ideology. attractive work.

    ReplyDelete