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.

7 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. Sir, I have tried your code it sends a file but when i extract that file the file is corrupted.

    ReplyDelete
  5. Will this code also enable file sharing over the internet?

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

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

    ReplyDelete