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

File Transfer using Socket Application in C# .NET 2.0

By , 26 Feb 2009
 

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)

About the Author

SumanBiswas
Web Developer
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
Hint: For improved responsiveness ensure Javascript is enabled and choose 'Normal' from the Layout dropdown and hit 'Update'.
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 2memberMember 28145687 Feb '13 - 2:46 
GeneralMy vote of 1memberstefano798030 Jan '13 - 9:14 
QuestionNicemembermoueen.sk23 Jan '13 - 23:28 
QuestionI love umemberarmanoo19 Nov '12 - 1:06 
Answerpiece of code that solves the issue of not getting the full file (into server class)memberAdi Constantin (Romania)24 Aug '12 - 3:46 
Questionimage transfer not workmemberesterph2 May '12 - 20:35 
Questiongreat jobgroupharisxxx8 Mar '12 - 2:25 
Questionword,pdf document are not opened properly...memberMember 858043129 Feb '12 - 19:43 
GeneralMy vote of 1memberLuciano Culacciatti9 Jan '12 - 2:24 
QuestionTCP buffer overflowmemberyang09323 Nov '11 - 5:13 
GeneralIt's Good but...memberosmel3316 Apr '11 - 19:16 
GeneralGreat Articlememberaerion25 Mar '11 - 17:33 
GeneralMy vote of 1memberH@is@here18 Mar '11 - 4:10 
GeneralFile transfer - File Sometimes transferred full n sometimes incompletememberMember 293046113 Mar '11 - 21:24 
GeneralFile transfer --file sometimes recevied correctly ,somtimes incompletememberMember 293046113 Mar '11 - 20:55 
With reference to the FileTransfer C# code on Code Project.
 
Im new to programming in C#.
 
I try to run it, sometimes i can get the transferred file with original size but sometimes with different sizes. Bytes missing whn file is receviced at the server.
 
I used many methods to find the solution but i was unable to get the solution..
 

I hope u will help me to give a solution.
 

Thank u Sir
 
Snehal
Generalplease help memembernasim1120 Feb '11 - 23:44 
GeneralThe example doesn't workmemberMessiah1634125 Oct '10 - 6:31 
GeneralMy vote of 1memberkamii4727 Sep '10 - 21:00 
GeneralhimemberMubi | www.mrmubi.com14 Aug '10 - 8:12 
GeneralGenerate Packet Headermemberbhavin chheda11 Jun '10 - 0:37 
Generalwe want help in BE projectmemberStunt Parmae4 Feb '10 - 17:52 
GeneralThanks for sharing it :)memberSrinath G Nath13 Jan '10 - 16:22 
GeneralMy vote of 1membersonqu5 Nov '09 - 17:09 
GeneralMy vote of 1memberSaksida Bojan14 Aug '09 - 8:29 
GeneralMy vote of 2memberzuraw26 Jul '09 - 21:18 

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

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