Click here to Skip to main content
Click here to Skip to main content

File Transfer using Socket Application in C# .NET 2.0

, 26 Feb 2009 CPL
Rate this:
Please Sign up or sign in to vote.
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 www.socketprogramming.blogspot.com.

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:

//FILE TRANSFER USING C#.NET SOCKET - SERVER
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
        sock.Bind(ipEnd); 
        //Bind end point with newly created socket.
    }
    public static string receivedPath;
    public static string curMsg = "Stopped";
    public void StartServer()
    {
        try
        {
            curMsg = "Starting...";
            sock.Listen(100);
            /* 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...";
            bWrite.Close();
            clientSock.Close(); 
            /* 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:

//FILE TRANSFER USING C#.NET SOCKET - CLIENT
class FTClientCode
{
    public static string curMsg = "Idle";
    public static void SendFile(string fileName)
    {
        try
        {
             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.";
                 return;
             }
             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 ...";
             clientSock.Connect(ipEnd); 
             /* Trying to connection with server. /
             curMsg = "File sending...";
             clientSock.Send(clientData);
             /* Now connection established, send client data to server. */
             curMsg = "Disconnecting...";
             clientSock.Close(); 
             /* 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." ;
             else
                 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 http://socketprogramming.blogspot.com/.

License

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

Share

About the Author

SumanBiswas
Web Developer
India India
No Biography provided
Follow on   Google+

Comments and Discussions

 
QuestionAddress incompatible PinmemberMember 1070414827-Mar-14 6:56 
QuestionCorrecting a Wrong Information PinmemberAman Thakur6-Jan-14 0:32 
Questiontanks PinmemberMujtaba2019-Dec-13 9:04 
Questionabout file trnsfer by socket in c# [modified] Pinmembermoslem128-Oct-13 23:47 
GeneralMy vote of 2 PinmemberMember 28145687-Feb-13 3:46 
GeneralMy vote of 1 Pinmemberstefano798030-Jan-13 10:14 
QuestionNice Pinmembermoueen.sk24-Jan-13 0:28 
QuestionI love u Pinmemberarmanoo19-Nov-12 2:06 
Answerpiece of code that solves the issue of not getting the full file (into server class) PinmemberAdi Constantin (Romania)24-Aug-12 4:46 
Questionimage transfer not work Pinmemberesterph2-May-12 21:35 
Questiongreat job Pingroupharisxxx8-Mar-12 3:25 
Questionword,pdf document are not opened properly... PinmemberMember 858043129-Feb-12 20:43 
GeneralMy vote of 1 PinmemberLuciano Culacciatti9-Jan-12 3:24 
QuestionTCP buffer overflow Pinmemberyang09323-Nov-11 6:13 
GeneralIt's Good but... Pinmemberosmel3316-Apr-11 20:16 
GeneralGreat Article Pinmemberaerion25-Mar-11 18:33 
GeneralMy vote of 1 PinmemberH@is@here18-Mar-11 5:10 
GeneralFile transfer - File Sometimes transferred full n sometimes incomplete PinmemberMember 293046113-Mar-11 22:24 
GeneralFile transfer --file sometimes recevied correctly ,somtimes incomplete PinmemberMember 293046113-Mar-11 21:55 
Generalplease help me Pinmembernasim1121-Feb-11 0:44 
GeneralThe example doesn't work PinmemberMessiah1634125-Oct-10 7:31 
GeneralMy vote of 1 Pinmemberkamii4727-Sep-10 22:00 
Generalhi PinmemberMubi | www.mrmubi.com14-Aug-10 9:12 
nice work, keep it up!
Mubshir Raza Ali
^^^^^^^^^^^^^^^^^^^^
http://www.mrmubi.com

GeneralGenerate Packet Header Pinmemberbhavin chheda11-Jun-10 1:37 
Generalwe want help in BE project PinmemberStunt Parmae4-Feb-10 18:52 
GeneralThanks for sharing it :) PinmemberSrinath G Nath13-Jan-10 17:22 
GeneralMy vote of 1 Pinmembersonqu5-Nov-09 18:09 
GeneralMy vote of 1 PinmemberSaksida Bojan14-Aug-09 9:29 
GeneralMy vote of 2 Pinmemberzuraw26-Jul-09 22:18 
GeneralMy vote of 1 PinmemberXmen W.K.17-Apr-09 15:40 
Generalgood Pinmembersatthutinhoc18-Mar-09 7:06 
Generalcan't read it.... PinmemberAdrian Pasik27-Feb-09 7:17 
GeneralProblem faced-sometimes can't get the original size of the file Pinmembercat ang17-Feb-09 21:19 
GeneralTried but only work until 7.11KB Pinmemberyukijocelyn6-Jul-08 23:49 
GeneralRe: Tried but only work until 7.11KB PinmemberSumanBiswas22-Jul-08 19:32 
GeneralRe: Tried but only work until 7.11KB Pinmemberyukijocelyn4-Aug-08 18:56 
GeneralRe: Tried but only work until 7.11KB PinmemberLoc Milkyway26-Jan-11 4:29 
QuestionIs a good example, but I have a prblem. Pinmemberfranferri29-Jun-08 0:21 
Generalask Q PinmemberAsArA25-Apr-08 1:06 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 27 Feb 2009
Article Copyright 2008 by SumanBiswas
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid