Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#

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 428.1K   25.3K   123   42
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:

C#
//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:

C#
//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)


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

 
GeneralIt's Good but... Pin
osmel3316-Apr-11 19:16
osmel3316-Apr-11 19:16 

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.