Click here to Skip to main content
15,439,373 members
Articles / Programming Languages / C#
Posted 1 Mar 2008


122 bookmarked

File Transfer using Socket Application in C# .NET 2.0

Rate me:
Please Sign up or sign in to vote.
2.32/5 (41 votes)
26 Feb 2009CPL2 min read
File transfer using C#.NET by using TCP Socket

Introduction & Background

When I tried to learn socket application in .NET (C#), I did not find any good ready made socket code to learn it. I had a problem and for that, I built a blog especially for socket application. Here I give just one application, but in my blog I have a few code examples to learn socket in C#.NET. You can find long and practical C# code on my blog at

I've written code to transfer a file from client to server using C#.NET socket application. That code has used TCP protocol to send file, that can run in LAN and WAN (Internet). It can send a small file from client to server, I've tested it with 1.5MB. But anyone can modify that code and can build an application to send a large file with multiple client support by a single server.

I'm giving an overview/steps to make a socket application. Here, there are two applications; one is Server and another is Client. At first, the server will open a port and will wait for a request from the client, and the client will try to connect to the server. After getting a connection request, the server will accept it and will make a successful connection. After a successful connection, the client will send data in byte array and the server will catch and hold it. Then, it will save these bytes. After successful data transfer, the server will save data and disconnect client.

I think after reading this code, one can understand how a socket application works. If anyone is unable to understand, then I request them to read my blog. If you still have any questions, please contact me via blog comment/mail and I will answer.

Using the Code

The complete server and client code is here in zip format. You can just download it and use it. I'm giving two code blocks of Server and Client.

The core code for Server application with some comments is as given below:

class FTServerCode
    IPEndPoint ipEnd; 
    Socket sock;
    public FTServerCode()
        ipEnd = new IPEndPoint(IPAddress.Any, 5656); 
        //Make IP end point to accept any IP address with port no 5656.
        sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        //Here creating new socket object with protocol type and transfer data type
        //Bind end point with newly created socket.
    public static string receivedPath;
    public static string curMsg = "Stopped";
    public void StartServer()
            curMsg = "Starting...";
            /* That socket object can handle maximum 100 client connection at a time & 
            waiting for new client connection /
            curMsg = "Running and waiting to receive file.";
            Socket clientSock = sock.Accept();
            /* When request comes from client that accept it and return 
            new socket object for handle that client. */
            byte[] clientData = new byte[1024 * 5000];
            int receivedBytesLen = clientSock.Receive(clientData);
            curMsg = "Receiving data...";    
            int fileNameLen = BitConverter.ToInt32(clientData, 0); 
            /* I've sent byte array data from client in that format like 
            [file name length in byte][file name] [file data], so need to know 
            first how long the file name is. /
            string fileName = Encoding.ASCII.GetString(clientData, 4, fileNameLen);
            /* Read file name */
            BinaryWriter bWrite = new BinaryWriter(File.Open
		(receivedPath +"/"+ fileName, FileMode.Append)); ; 
            /* Make a Binary stream writer to saving the receiving data from client. /
            bWrite.Write(clientData, 4 + fileNameLen, 
		receivedBytesLen - 4 - fileNameLen);
            /* Read remain data (which is file content) and 
            save it by using binary writer. */
            curMsg = "Saving file...";
            /* Close binary writer and client socket */
            curMsg = "Received & Saved file; Server Stopped.";
        catch (Exception ex)
            curMsg = "File Receiving error.";

The code for client application is as follows:

class FTClientCode
    public static string curMsg = "Idle";
    public static void SendFile(string fileName)
             IPAddress[] ipAddress = Dns.GetHostAddresses("localhost");
             IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 5656); 
             /* Make IP end point same as Server. */
             Socket clientSock = new Socket(AddressFamily.InterNetwork, 
		SocketType.Stream, ProtocolType.IP);
             /* Make a client socket to send data to server. */
             string filePath = "";
             /* File reading operation. */
             fileName = fileName.Replace("\\", "/");
             while (fileName.IndexOf("/") > -1)
                 filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
                 fileName = fileName.Substring(fileName.IndexOf("/") + 1);
             byte[] fileNameByte = Encoding.ASCII.GetBytes(fileName);
             if (fileNameByte.Length > 850 * 1024)
                 curMsg = "File size is more than 850kb, please try with small file.";
             curMsg = "Buffering ...";
             byte[] fileData = File.ReadAllBytes(filePath + fileName); 
             /* Read & store file byte data in byte array. */
             byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length]; 
             /* clientData will store complete bytes which will store file name length, 
             file name & file data. */
             byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
             /* File name length’s binary data. */
             fileNameLen.CopyTo(clientData, 0);
             fileNameByte.CopyTo(clientData, 4);
             fileData.CopyTo(clientData, 4 + fileNameByte.Length);
             /* copy these bytes to a variable with format line [file name length]
             [file name] [ file content] */
             curMsg = "Connection to server ...";
             /* Trying to connection with server. /
             curMsg = "File sending...";
             /* Now connection established, send client data to server. */
             curMsg = "Disconnecting...";
             /* Data send complete now close socket. */
             curMsg = "File transferred.";
        catch (Exception ex)
             if(ex.Message=="No connection could be made because the target machine 
                actively refused it")
                 curMsg="File Sending fail. Because server not running." ;
                 curMsg = "File Sending fail." + ex.Message;

I hope you understand how a file can be sent from client to server via TCP socket in C#. Here I've write simple code to send a single file, but it’s the basic code. By modifying that code, multiple files can be sent from client to server, and by incorporating thread technology, that server can handle multiple clients at a time. And by using both end binary writer & reader can send large files too. Here, we will give a small problem for TCP buffer overflow that needs to send data after slicing. To know more on Socket programming, please visit my blog at


This article, along with any associated source code and files, is licensed under The Common Public License Version 1.0 (CPL)

Written By
Web Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

QuestionChat App Application Pin
Hưng Mai Phạm Quốc24-Nov-21 22:10
MemberHưng Mai Phạm Quốc24-Nov-21 22:10 
Questionhow to manage code for transfer video and pdf file? Pin
Member 137896981-May-18 19:32
MemberMember 137896981-May-18 19:32 
Questionaddress imcompatible Pin
Subha Priya5-Mar-18 21:19
MemberSubha Priya5-Mar-18 21:19 
QuestionAddress incompatible Pin
Member 1070414827-Mar-14 5:56
MemberMember 1070414827-Mar-14 5:56 
QuestionCorrecting a Wrong Information Pin
Aman Thakur5-Jan-14 23:32
professionalAman Thakur5-Jan-14 23:32 
Questiontanks Pin
Mujtaba2019-Dec-13 8:04
MemberMujtaba2019-Dec-13 8:04 
Questionabout file trnsfer by socket in c# Pin
moslem128-Oct-13 22:47
Membermoslem128-Oct-13 22:47 
GeneralMy vote of 2 Pin
SohrabFarzaneh7-Feb-13 2:46
MemberSohrabFarzaneh7-Feb-13 2:46 
GeneralMy vote of 1 Pin
stefano798030-Jan-13 9:14
Memberstefano798030-Jan-13 9:14 
QuestionNice Pin
moueen.sk23-Jan-13 23:28
Membermoueen.sk23-Jan-13 23:28 
QuestionI love u Pin
armanoo19-Nov-12 1:06
Memberarmanoo19-Nov-12 1:06 
Answerpiece of code that solves the issue of not getting the full file (into server class) Pin
Adi Constantin (Romania)24-Aug-12 3:46
MemberAdi Constantin (Romania)24-Aug-12 3:46 
Questionimage transfer not work Pin
esterph2-May-12 20:35
Memberesterph2-May-12 20:35 
Questiongreat job Pin
harisxxx8-Mar-12 2:25
Memberharisxxx8-Mar-12 2:25 
Questionword,pdf document are not opened properly... Pin
Member 858043129-Feb-12 19:43
MemberMember 858043129-Feb-12 19:43 
GeneralMy vote of 1 Pin
Luciano Culacciatti9-Jan-12 2:24
MemberLuciano Culacciatti9-Jan-12 2:24 
QuestionTCP buffer overflow Pin
yang09323-Nov-11 5:13
Memberyang09323-Nov-11 5:13 
GeneralIt's Good but... Pin
osmel3316-Apr-11 19:16
Memberosmel3316-Apr-11 19:16 
GeneralGreat Article Pin
aerion25-Mar-11 17:33
Memberaerion25-Mar-11 17:33 
GeneralMy vote of 1 Pin
H@is@here18-Mar-11 4:10
MemberH@is@here18-Mar-11 4:10 
GeneralFile transfer - File Sometimes transferred full n sometimes incomplete Pin
Member 293046113-Mar-11 21:24
MemberMember 293046113-Mar-11 21:24 
GeneralFile transfer --file sometimes recevied correctly ,somtimes incomplete Pin
Member 293046113-Mar-11 20:55
MemberMember 293046113-Mar-11 20:55 
Generalplease help me Pin
nasim1120-Feb-11 23:44
Membernasim1120-Feb-11 23:44 
GeneralThe example doesn't work Pin
Messiah1634125-Oct-10 6:31
MemberMessiah1634125-Oct-10 6:31 
GeneralMy vote of 1 Pin
KamranShahid27-Sep-10 21:00
MemberKamranShahid27-Sep-10 21:00 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.