A Client Server File Sharing Application



This blog post is a client/server file sharing or transfer application in C#, the application is made up of two projects, it can be tested on a single computer but, its capability will be best seen if tested on two computers, one running as a client while the other is a server.

Before we dive into coding, its essential to understand Socket which is the most important aspect of network programming.

Socket is an object that represents a low level access point to the Internet Protocol(IP) stack, it is used to send and receive data, thus it can be opened and closed, the data to be sent is  always sent in block known as Packet.

Packets must contain the IP address of both the source of the packets and the destination computer where the data is being sent, and optionally it may contain a Port number. A port number is between 1 and 65,535. A port is a communication channel or endpoints on which computers can communicate. It is always recommended that programs use port number higher than 1024 to avoid conflicts with other applications running on the system, because no two applications can use the same port.

Packets containing port numbers can be sent using UDP(User Datagram Protocol) or TCP/IP(Transmission control protocol). UDP is easier to use than TCP because TCP is more complex and has longer latencies, but when the integrity of the data to be transferred is more important than performance, then TCP is prefered to UDP, and thus for our file sharing application TCP/IP will be used because it guarantees that our file does not become corrupt while being transfered and if during the transmission process a packet is loss, it is retransmitted thus making sure that our file integrity is maintained.

Thus, this application will allow you to send any file from one computer to another, personally I have used it to send a 350mb file from one desktop PC to another.

Now to get started, create two new windows forms applications one named FileSharingServer and the other FileSharingClient.

Now, for the FileSharingClient windows form application add three textboxes and two buttons to the form just like the screen below.

filesharingclient

Rename the textboxes and buttons appropriately.
This is the code for the file sharing client application

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.Threading.Tasks;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.IO;

namespace FileSharingClient
{
    public partial class Form1 : Form
    {
        private static string shortFileName = "";
        private static string fileName = "";
        public Form1()
        {
            InitializeComponent();
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Title = "File Sharing Client";
            dlg.ShowDialog();
            txtFile.Text = dlg.FileName;
            fileName = dlg.FileName;
            shortFileName = dlg.SafeFileName;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string ipAddress = txtIPAddress.Text;
            int port = int.Parse(txtHost.Text);
            string fileName = txtFile.Text;
            Task.Factory.StartNew(() => SendFile(ipAddress,port,

             fileName,shortFileName));
            MessageBox.Show("File Sent");
        }

        public void SendFile(string remoteHostIP, int remoteHostPort

           , string  longFileName, string shortFileName)
        {
         try
         {
          if(!string.IsNullOrEmpty(remoteHostIP))
            {
             byte[] fileNameByte = Encoding.ASCII.GetBytes

             (shortFileName);
             byte[] fileData = File.ReadAllBytes(longFileName);
             byte[] clientData = new byte[4 + fileNameByte.Length

                + fileData.Length];
             byte[] fileNameLen = BitConverter.GetBytes(

              fileNameByte.Length);
             fileNameLen.CopyTo(clientData, 0);
             fileNameByte.CopyTo(clientData, 4);
             fileData.CopyTo(clientData, 4 + fileNameByte.Length);
             TcpClient clientSocket = new TcpClient(remoteHostIP,

              remoteHostPort);
             NetworkStream networkStream = clientSocket.GetStream();
             networkStream.Write(clientData, 0, clientData.GetLength

              (0));
             networkStream.Close();
           }
         }
         catch
         {

         }
        }
    }
}

    
 
Note the following namespaces were added to the windows form application

    System.Threading.Tasks; 
the namespace above is used to include the .Net Parallel computing classes

   System.Net;
   System.Net.Sockets;
   System.Net.NetworkInformation;

the three namespaces  above contain the .Net classes used for Network programming

    System.IO;
the namespace above contains classes used for file operations

When the browse button is clicked an object of OpenFileDialog is created to open a dialog to get the file name of the file to be sent. When the send button is clicked, the SendFile method is called and handled in parallel so that the main form user interface does not get frozen while the file is being sent and the processors are fully utilized in a multi-core environment.

The SendFile method accepts IP address and port number of the destination computer as well as the file path and file name. Both the file name and the file are converted to bytes and sent to the destination computer using the TCPCLient and NetworkStream classes object created.

The user interface of the file sharing client application is shown below when run.

filesharingclient2


The source code for the server is


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;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.IO;
using System.Threading.Tasks;

namespace FileSharingServer
{
    public partial class Form1 : Form
    {

        public delegate void FileRecievedEventHandler(object source,

          string fileName);

        public event FileRecievedEventHandler NewFileRecieved;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.NewFileRecieved+=new FileRecievedEventHandler
            (Form1_NewFileRecieved);
        }

        private void Form1_NewFileRecieved(object sender, string
         fileName)
        {
            this.BeginInvoke(
            new Action(
            delegate()
            {
                MessageBox.Show("New File Recieved\n"+fileName);
                System.Diagnostics.Process.Start("explorer", @"c:\");
            }));
        }

        private void btnListen_Click(object sender, EventArgs e)
        {
            int port = int.Parse(txtHost.Text);
            Task.Factory.StartNew(() => HandleIncomingFile(port));
            MessageBox.Show("Listening on port"+port);
        }

        public void HandleIncomingFile(int port)
        {
          try
            {
                TcpListener tcpListener = new TcpListener(port);
                tcpListener.Start();
                while (true)
                {
                  Socket handlerSocket = tcpListener.AcceptSocket();
                    if (handlerSocket.Connected)
                    {
                     string fileName = string.Empty;
                     NetworkStream networkStream = new NetworkStream

                      (handlerSocket);
                     int thisRead = 0;
                     int blockSize = 1024;
                     Byte[] dataByte = new Byte[blockSize];
                     lock (this)
                     {
                      string folderPath = @"c:\";
                      handlerSocket.Receive(dataByte);
                      int fileNameLen = BitConverter.ToInt32(dataByte,

                       0);
                      fileName = Encoding.ASCII.GetString(dataByte, 4,

                       fileNameLen);
                      Stream fileStream = File.OpenWrite(folderPath +

                       fileName);
                      fileStream.Write(dataByte, 4+fileNameLen,(

                       1024-(4+fileNameLen)));
                      while (true)
                      {
                       thisRead = networkStream.Read(dataByte, 0,

                        blockSize);
                       fileStream.Write(dataByte, 0,thisRead);
                       if (thisRead == 0)
                        break;
                      }
                      fileStream.Close();

                    }
                    if (NewFileRecieved != null)
                     {
                       NewFileRecieved(this, fileName);
                     }
                    handlerSocket = null;
                    }
                }

            }
            catch
            {

            }
        }
    }
}

   



 filesharingserver filesharingserver2

At the file sharing server application, a port number is supplied, on which the server will be listening to an income file to be recieved.

Just like the file sharing client application, the start listening button when clicked, invokes the HandleIncomingFile method in parallel. A TcpListener object is created to start listening for incoming file at the specified port, when a connection is received the  a file with the same name as the file sent from the client is reconstructed from the received bytes and saved to the C drive and then an event is fired to indicate on the server user interface that a new file has been received.

When the event is fired, all subscribers to the event are notified and in this case the event handler method Form1_NewFileRecieved is invoked and the code to display a message box and open the folder containing the file received is  wrapped around  the form BeginInvoke method to avoid thread errors.

The Complete source code of the two applications is available for download Here




Share this page on


42 Comment(s)   90 People Like(s) This Page   Permalink  

 Click  To Like This Page

comments powered by Disqus



Older Comment(s)

Posted by    Simon

Friday, February 10, 2012    7:08 PM

hi. i have followed the example but it dosent work. i have done the Client and server but no files can be recived...




Posted by    Ayobami Adewole

Friday, February 10, 2012    9:04 PM

@Simon I have tested it and so have many other people who have given their testimonies, it works. Try turn firewall off on the server and try it again, if it still doesnot work, try and ping the server from the client to see if the two computers you are using can communicate at all




Posted by    nikhil

Sunday, March 25, 2012    4:48 PM

sir i am final year student my project is based on same file sharing system, need some extension from you sir.... i want to modify my application, by now my application communicates between 1 to 1 i.e server to client n vice-versa but now i want to make it with multiple clients..need some help!!!




Posted by    Ayobami Adewole

Tuesday, March 27, 2012    11:24 AM

@niknil Its multicasting that will solve the problem or better still you can try WCF, but I will recommend you search codeproject and msdn there are a lot of articles that can be of help




Posted by    Aarthi

Wednesday, April 04, 2012    11:11 AM

When im using this program Im unable to run the program as in the function public void HandleIncomingFile(int port) The server is waiting for accepting Client connection in the place Socket handlerSocket = tcpListener.AcceptSocket(); and because of that im unable to proceed further....




Posted by    Ayobami Adewole

Thursday, April 05, 2012    8:01 PM

@Aarthi this line of code Socket handlerSocket = tcpListener.AcceptSocket(); waits for an incoming connection, it will not proceed further until a connection has been established, I mean until a client computer connects to the server computer.




Posted by    taki

Saturday, May 05, 2012    2:01 PM

hi,first i wanna say thanks for ur hard work. but i have a question i hope u can help me ?! can i use my own computer as client and server at the same time..i tried to put in the ip address field this IP 127.0.0.1 ( that from what i know is used when i want my computer to act as the client & the server at the same time) every thing is working accept for the final step NO message box is displayed opening the folder containing the picture i have sent and where can i exactly find the picture that i have sent




Posted by    Lura

Sunday, May 06, 2012    7:28 AM

Hi! where can i download this project, like the full project




Posted by    Ayobami Adewole

Tuesday, May 08, 2012    5:45 AM

@Taki sorry my reply is coming late I have been busy lately, you can use your computer as both the client and server, it will still work, as for where the file will be, the sent file will be dropped in the root folder of you C: drive, you can change it in the code to wherever you like.




Posted by    Ayobami Adewole

Tuesday, May 08, 2012    5:48 AM

@Lura you can download the application using this link, http://ayobamiadewole.com/Blog/Files/FileSharingSharing.rar




Posted by    chamara

Tuesday, May 15, 2012    8:36 AM

this very useful information can this project use full this way after send data to the server to automatically resend data to back to the client after severer done some calculation finish 2)do u use any webserver(service )to do such thing?




Posted by    Ayobami Adewole

Wednesday, May 16, 2012    12:28 PM

@Chamara, that is quite possible, communication can be from the client to the server and the other way round. The code doesnot use webservice, it uses .Net TCP/IP classes, but you can equally use WCF to achieve the same purpose.




Posted by    zeshan ajmal

Tuesday, May 29, 2012    7:22 AM

first i wanted to thank you for this. I've been trying same but constantly getting the exception"access to path is denied". Well your code did it! May i ask you to help me with that exception? Looking forward for your reply




Posted by    zeshan ajmal

Tuesday, May 29, 2012    7:38 AM

I also wanna ask a thing, what is the reason behind giving same name to delegate and ref var of event? I did not get this point




Posted by    Ayobami Adewole

Thursday, May 31, 2012    9:41 PM

@Zeshan its good to hear that, as pertaining to your exception, its likely your code is trying to access a path where it currently does not have permission, you can see if elevating the application to an admin will solve it. Its not the same name, "NewFileRecieved" its an object of the delegate, the delegate was not used directly an object of it was created.




Posted by    Kiran

Thursday, July 05, 2012    8:21 AM

Respected Sir i am using .net 3.5 and it does not support Reference System.threading.task. So i cannot use this line "Task.Factory.StartNew(() => HandleIncomingFile(port)); MessageBox.Show("Listening on port"+port);" Is there any other way of writing this code?




Posted by    Ayobami Adewole

Thursday, July 05, 2012    2:25 PM

@Kiran you can use Threading in 3.5 to achieve this as well, that HandleIncomingFile() method can be placed on a separate thread and things will work file




Posted by    jitu

Friday, August 17, 2012    6:27 AM

thank you sir its working fine




Posted by    jitu

Friday, August 17, 2012    6:36 AM

Dear sir actually i am new to c# i was develop some mobile computer application but my device support only visual studio 2005 & your application is working on 2008 so can you please provide me a code for file sharing (client/server)which support visual studio 2005




Posted by    Ayobami Adewole

Friday, August 17, 2012    9:03 PM

@Jitu, to make the code run using VS 2005, replace Task.Factory.StartNew() line of code with an equivalent threading implementation, it should work with that




Posted by    jitu

Monday, September 17, 2012    5:17 AM

thank you sir iwill check & revert you




Posted by    swetha

Wednesday, September 26, 2012    12:57 PM

hello sir I need system.threading.task dll file(framework 3.5) kindly fwd to my mailid,if nt give me code for file transfering from client to server......thanku




Posted by    chinna

Thursday, October 04, 2012    7:21 PM

hello sir, my project is "data leakage detection" i want to upload a file n send it to other pc (both r connecting lan cable ) but when i upload n click snd buton , the records are inserted into table bt my error is 'file sending fail,a connection attempt fail' plz give a soltn




Posted by    Ayobami Adewole

Thursday, October 04, 2012    8:41 PM

@Chinna check if both computers are connected, try and ping both pcs IP addresses from each other and see if they can communicate, because the error is most probably a communication error




Posted by    chinna

Monday, October 08, 2012    6:19 PM

hi sir, now im connecting 2systmes in lan dat works perfectly ,but my problem z im sending only small size files only like 9kb... but i want to send large files also please give me a sol..




Posted by    chinna

Tuesday, October 09, 2012    6:06 PM

hi sir, in my project my problem is im sending small files but if i send large file n videos sending ,files sending specified location but not opened file is damaged and could n't be repaired plz give sol asap




Posted by    sridar

Wednesday, October 10, 2012    6:16 PM

hi sir ,im creating c#windows app setup file ,install it to other pc ,when i run dt setup the login form cn't login properly , my error is a network related or instance spesific error occured while establishng a connection to sql. the server was not found r not accesible verify that the insatnce name is correct and that sql server is configured to allow remote connection.....plz give sol for me asap early




Posted by    Ayobami Adewole

Wednesday, October 10, 2012    9:53 PM

@Chinna are you using the source code here, if yes, I have tested it and so have others, it does maintain the integrity of the file when sent, and it does not corrupt it, I have used it to send a file of 400MB in size.




Posted by    Ayobami Adewole

Wednesday, October 10, 2012    9:57 PM

@Sridar the problem is in your connection string check whether the correct sql server instance was specified in the connection string




Posted by    sridar

Thursday, October 11, 2012    11:05 AM

hi , in prjct im using c#.net . i create c#.net win form setup file n install n run other system bt my prblm is it vl open login form but when i enter agentid ,name ,psw it's nt wrk properly,i set all of conctn string ,datasource r correctly afr setng al thease proprties den only i create setup file but my error is a network related or instance spesific error occured while establishng a connection to sql. the server was not found r not accesible verify that the insatnce name is correct and that sql server is configured to allow remote connection.....plz give sol for me asap early




Posted by    Akshay Jindal

Tuesday, November 06, 2012    8:03 AM

Thnx dude........its working Very helpful




Posted by    Ritu

Thursday, November 22, 2012    7:09 AM

Sir, as one of the computer is behaving like a server so is it necessary to install software for making a pc behaving like a server? and are the devices connected to a particular network over which they are communicating?




Posted by    Jussi

Tuesday, November 27, 2012    10:09 PM

Hello Ayobami Adewole! Can I get example next program: I have two computers which should sen data each other. And if other computer example press button1 on own form, it will make some changes to other computers form. I try to do card game where all users changes show also to other users who use the same game on other pc. That can be hard to understand but if you could help? :) :) :)




Posted by    Ayobami Adewole

Wednesday, November 28, 2012    7:32 AM

What you want to achieve is Network Multicast, the application here does unicast.




Posted by    Safak

Monday, December 03, 2012    10:22 AM

Hi Ayobami, Thanks for project. I tested and working.




Posted by    phanindra

Tuesday, December 04, 2012    8:17 AM

haloo sir these program working extent ,but i want display client ips who r connected to server, in server listbox please mail me that code sir thakks




Posted by    Evans Boma

Saturday, December 29, 2012    2:51 PM

Hello, I need to learn certain things 4rm u. they include 1. How to develop Client Server Applications 2.Reporting with Crystal report. 3. Printing reports, mailing reports, converting reports to pdf and Excell. plz do send me a mail. Thanks




Posted by    Jose Raúl

Monday, January 07, 2013    6:17 AM

Your app works perfectly, thank you very much. I even tried it outside my LAN. Thanks




page