File Transfer Using C#

Published on by Inno Design

Today as we told you last time going to tell you how we can implement file transfer in LAN

This will let you allow file transferring even through TELNET.

SERVER:

So let’s start with designing the server part.

for server we’ll just need a label and a List Box like the previous one

Difference is Just in coding only.

So this is how it gonna look like

image

For File transferring we prefer to use TCP because it confirms the complete and correct order of transfer unlike UDP which just gives preference to speed.

So here we start coding from

Using statements are as follows

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Threading;
using System.Net;
using System.Net.Sockets;

Server Variables are like this

List<object> AiSocket= new List<object>();

delegate void additem(object obj);

delegate void additem1(string str);

The form load event of the form will be like this

private void Form1_Load(object sender, EventArgs e)
{
IPHostEntry ip = Dns.GetHostByName(Dns.GetHostName());
label1.Text = “My Ip Is ” + ip.AddressList[0].ToString();
Thread thrdlistener = new Thread(new ThreadStart(listen));
thrdlistener.Start();
}

1st line returns the IpHostEntry, with that we extract the Own IP address. Note that we are programming for LAN so the IP address we’ll get from here will not be the public IP which is provided to us by our ISP, Its our Private IP which will be unique in our Local Network.

The process of file transferring is easy to understand. Please note that it is very basic application. In this we just have described the way of file transferring over LAN.

In this process we’ll have a client like last time and a server. There’ll be a tcpListener  object which will listen to one port and when it’ll get any message it’ll create a File and Ask OS for a Lock over that file and will write the content of the message on that file.

void listen()
{
TcpListener tcplisten = new TcpListener(1095);
tcplisten.Start();
while (true)
{
TcpClient handlerSocket = tcplisten.
AcceptTcpClient();
if (handlerSocket.Connected)
{
if (listBox1.InvokeRequired)
{
additem mydel = new additem(additem3);
listBox1.BeginInvoke(mydel,handlerSocket);
}
lock (this)
{
AiSocket.Add(handlerSocket);
}
Thread thdhandler = new Thread(new ThreadStart(handlerThread));
thdhandler.Start();
}
}

}

Here 1st Line shows an Object of TCPListener which listen to port 1095 in the previous Example we took a UDPlient and listen to port 8080. in 2nd line listener start listening.

then An infinite loop starts. when tcp listener will be connected with some client (can be TELNET) then it’ll return a TCP client object as shown in 4th line.

Now the when the if statement is true we’ll be inserting that member into listbox.

Now we can’t do that using this thread as listbox were not created under scope of this thread it was created under scope of Main thread, so we’ll use shown technique for doing that.

check for if invokeis required if yes then use begin invoke method and pass a delegate that matches with the method in term of signature where we’ll add member into ListBox.

Now as we get the message another thread is created to write the file on destination directory.

For writing file the method is like this

void handlerThread()
{
TcpClient handlerSocket = (TcpClient)AiSocket[AiSocket.Count - 1];
NetworkStream Nw = new NetworkStream(handlerSocket.Client);
int thisRead = 0;
int Blocksize = 1024;
Byte[] dataByte = new Byte[Blocksize];
lock (this)
{
Stream strm = File.OpenWrite(“C:\\readme.txt”);
while (true)
{
thisRead = Nw.Read(dataByte, 0, Blocksize);
strm.Write(dataByte, 0, thisRead);
if (thisRead == 0)
break;
}
strm.Close();
if (listBox1.InvokeRequired)
{
additem1 mydel = new additem1(additem2);
listBox1.BeginInvoke(mydel,”Trasnfer Done”);
}
handlerSocket = null;
}
}

Now we need a little concentration over this method.

TcpClient handlerSocket = (TcpClient)AiSocket[AiSocket.Count - 1];
this line will return the tcpclient that we received most recently. in next line we are receiving a Network stream from which we’ll get the content of the message received in Bytes.

Another variable id offset point and next one is block size for file Writing.

in next line we asked for the lock and created a file.

Now it’ll run an Infiniteloop.

using Network stream we got the Message in Byte form. and then after we wrote that on the fileand then got out of the loop

stream is closed and another work we are left is to insert another item in List box that we are done with the transfer.

here’s the method for inserting Items Into ListBox

void additem3(object obj)
{
TcpClient handlerSocket = (TcpClient)obj;
listBox1.Items.Add(handlerSocket.Client.RemoteEndPoint.ToString() + ” Connected”);
}
void additem2(string str)
{
listBox1.Items.Add(str);
}

So here we completed Our Server

Client:

Now let’s start with Client.

imageSo as you can say we just need two buttons and one text box placed as shown.

So Let’s start with Coding that’s our game for sure.

The using statements are as Follows

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Net.Sockets;

On the click event of browse button all we need to do is to open a open file dialog box and get path of the file we want to transfer. Here’s the click event

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog ofpd = new OpenFileDialog();
ofpd.ShowDialog();
textBox1.Text = ofpd.FileName;
}

We extracted the path and put that into our text box.

Now we have to send this file to our server here’s the code for sending

private void button2_Click(object sender, EventArgs e)
{
Stream Fs = File.OpenRead(textBox1.Text);
Byte[] buffer = new Byte[Fs.Length];
Fs.Read(buffer, 0, buffer.Length);
TcpClient socket = new TcpClient(“Localhost”, 1095);
NetworkStream nw = socket.GetStream();
nw.Write(buffer, 0, buffer.Length);
nw.Close();
}

we took the file in stream, read the stream and put the content into byte form so that we could transfer that over network.

In next line we took a TCPClient object and attempt connection to the server on port 1095. If the server is running there, it’ll connect otherwise it’ll return an exception.

TCPClient’s Constructor takes Two parameter (the method is overloaded so other options are also available you are advised to explore other too), One is the address of the server’s pc and other is the port number which server is listening to.

We created a Network Stream and using that we sent the data and then closed the networkstream. It is that easy.

You can transfer or write anything to the file using TELNET as well.

Just go to run and write “telnet”

a command window will open type there ‘o localhost 1095” for our case. and start writing whatever you want.

So hope you enjoyed this Post.

Please leave your questions and please give suggestions.

Published on Networking

Comment on this post

David 12/10/2011 04:54

Hi, thanks for your great work here. Btw, Just curious whether socket is able to write multiple files in single stream? As in, filename followed by file extension followed by file content (whatever
file it can be)? Any feedback would be greatly appreciated. XD