A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
File transfers through networks and the InternetThis tutorial will teach you how to send and receive files from your local system to a server, either through a network or through the Internet, using C# and streaming connections. This tutorial is also helpful for learning the basics of networking using the .NET Framework. |
On Wednesday, May 3rd 2006 at 08:28 PM By Andrew Pociu (View Profile) ![]() ![]() ![]() ![]() (Rated 4.6 with 22 votes) |
||
|
In this tutorial we're going to build a very interesting .NET application, and based on the code here you will hopefully be able to build various applications or to help you with extending your current work. Before digging into the code, you should know that the code you see in this tutorial and in the attached project resumes to only the strict functionality of exchanging files between two computers using the .NET Framework. If you want to integrate this into a real-life application, you will need to put more effort into this code since currently it lacks crash prevention and recovery, testing on multiple systems, against firewalls, etc. For using this code I recommend that you use two different computers, either on a network or on the Internet. The firewall on both computers (but especially on the server computer) should be shut down to prevent the port we're going to use being locked. However, the beauty of this application is that you can use a single computer to test it; you can run the server and the client application on the same computer and transfer files from one path to another. Speaking of server and client, in this tutorial we're going to build two applications. One is the server that listens for connections on a certain port and receives files in streams and then saves them to the local C:\ drive, and one is the client that connects to the server application on the same port the server is listening to. The application is developed using .NET Framework 2.0 in Visual Studio 2005, however you should be able to convert it to .NET Framework 1.1 rather easily. How the file transfer worksFirst we need to create the server application. The server application pictured below under the arrow will be the one receiving a file from a remote computer and storing it on the hard drive. Prior to receiving the actual file, it will receive information about the file: the file name and size. This information will be passed by the client, and it will be retrievied using the FileInfo class from the .NET Framework.The first thing you need to do is to enter a port (815 is normally not taken on most computers) and click on "Start Server". You will see a message "Starting the server..." shortly followed by "The server has started. Please connect the client to 192.168.0.1". Of course, the IP will probably differ in your case, so you should write it down because you will need to enter it in the client application later. At this time you should leave the server application running and switch to the client application (Network File Sender). The client application will first need to connect to the server, so you need to press the "Connect" button. Before pressing the button however, please make sure that you entered the same port as in the server window, and the IP that you were prompted to enter. Hopefully you will not experience any problems and you will see the "Successfully connected to server" message. After that you will be able to press the "Send New File" button which will let you browse to a file. Right after you pick the file, you will see that the progress bar on the server (Network File Receiver) starts making progress and the file is being transfered. So where is the file? By default the code saves it to C:\ so look for it there. After the file is sent the client and server-side streams and connections are closed to release resources. To prepare for an upcoming connection, the server then starts again (of course, you can change this to your liking). ![]()
We will start with creating the server, since we first need an application to listen for connections before we actually send a file. |
|||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
|||
|
|||
Current Commentsman.. u are great!
thx!
im sorry to rain on you but i have been programing C# for 2days now[WOW] and i have a problem with your code when it comes to creating the thread:
you need to use a slightly longer but safer method of
{
thrDownload = new Thread( new ThreadStart(StartReceiving));
thrDownload.Start();
}
sorry bout that!
also you may want to terminate the thread when you stop the server!
Its great.
But you avoid situations like here:
Server is able to accept new connection only when it\'s not receiving data.
You should rather accept connection, pass Client to separate thread, and in while loop start accepting new connection, than start accepting new connection after job is done.
Hi! This tutorial is great!
But if I connect more clients to the server (Client1, Client2 and Client3), and send data with the Client1, how can the server send this data to Client2 and Client3? E.g. in a messenger program, where the client1 writes something, send it to the server, and the server sends it to all of the connected clients. How can I do this? Please help!
Good One..Thank You
so smart and so great ...
but you had missed some thing that is ,
if you try to open the task manager an look at the processes you will notice that the client application is still running(this case happens if you close the client and still keep server running ) ,
so i suggest to add this to your application in[ from closing event]
Environment.Exit(0);
this will make your application work efficiently
good luck
Nice.
piterfromwawa/others:
it is only an example to show how to transfer files from 1 server to 1 client. You would surely implement more threads if programming an an actual file transfer server... Using the example here, you could easily throw something together that would allow multiple client connections, etc.
rpG:
As piter said: after a client connects, hand off the connection to another thread (make sure the client stays connected) and listen for other connections, when another client connects, hand that off to another thread, etc. Keep track of the connected clients (in a list/array, if the client disconnects remove it from array) then send the file to all connected clients when the send button is pressed.
Sorry to ask you these elimentary questions but I am but a novice in C#.
Do I run the server and client code on seperate instances of VS?
Then I get an error when I try to send any file type other than txt. Something with the int64 part of the code. It says "string not in correct form". Does this code send all types of files, i.e. images etc.?
Thanks!
C it iz working fine on the loacal host ,but the same code whenever i run on 2 different machines ,i get an eror ,that input is not in correct format .it gives the error for file size
First of all I would like to thank Andrei Pociu for this great program and explanation... I am trying to utilize it for my needs...
As Mahmoud Faress said, the Environment.Exit(0); is needed...
Morever, I don\'t know about the others but the file transfer did not work correctly... I am not an advanced C# user, but after a lot of time spent debugging the program, I came to better understand it\'s logic, and thus understand the error of FormatException...
Same occurs to me, and what the reason seems to be that first a byte array is created to store 2048 bytes from which the filename will be taken to inform the Server...
After which, the client should send another 2048 bytes containing the file size. The problem (at least in my case) is that apart from the bytes used to store the file size, the rest are used to store the other file data.. Ex. if I want to send a txt file of 2048 bytes starting as \"Trapper\" the 2048 bytes would contain (in their decimal format):
[0] = 2
[1] = 0
[2] = 4
[3] = 8
[4] = T
[5] = r
[6] = a
[7] = p
[8] = p
[9] = e
[10] = r
The first four elements correctly contain the file size, but the rest should be zeros, and not contain the file data... That is why the FormatException occurs, since text cannot be converted to integer... I still haven\'t quite solved the problem, but either the user has to enter the number of bytes that he want to be read (thus the number of bytes used to store the file size) or else correct the buffer data...
Apart from this, even though I haven\'t started working on it, at first sight, the progress bar uploading seems to be incorrect, since the amount of bytes transfered seems to be linked to the string containing the file location...
I don\'t know if this is just me, but I think that is how everyone should be having the program... I\'ll send later (if I\'ll have the problem solved), in the mean time I\'d love to hear if anyone has had the program working fine ... after being tested, or if anyone have solved any of the problems (as mine).
First of all I would like to thank Andrei Pociu for this great program and explanation... I am trying to utilize it for my needs...
As Mahmoud Faress said, the Environment.Exit(0); is needed...
Morever, I don\'t know about the others but the file transfer did not work correctly... I am not an advanced C# user, but after a lot of time spent debugging the program, I came to better understand it\'s logic, and thus understand the error of FormatException...
Same occurs to me, and what the reason seems to be that first a byte array is created to store 2048 bytes from which the filename will be taken to inform the Server...
After which, the client should send another 2048 bytes containing the file size. The problem (at least in my case) is that apart from the bytes used to store the file size, the rest are used to store the other file data.. Ex. if I want to send a txt file of 2048 bytes starting as \"Trapper\" the 2048 bytes would contain (in their decimal format):
[0] = 2
[1] = 0
[2] = 4
[3] = 8
[4] = T
[5] = r
[6] = a
[7] = p
[8] = p
[9] = e
[10] = r
The first four elements correctly contain the file size, but the rest should be zeros, and not contain the file data... That is why the FormatException occurs, since text cannot be converted to integer... I still haven\'t quite solved the problem, but either the user has to enter the number of bytes that he want to be read (thus the number of bytes used to store the file size) or else correct the buffer data...
Apart from this, even though I haven\'t started working on it, at first sight, the progress bar uploading seems to be incorrect, since the amount of bytes transfered seems to be linked to the string containing the file location...
I don\'t know if this is just me, but I think that is how everyone should be having the program... I\'ll send later (if I\'ll have the problem solved), in the mean time I\'d love to hear if anyone has had the program working fine ... after being tested, or if anyone have solved any of the problems (as mine).
hi Trapper
I am also experiencing the same problem and found ur explanation to be interesting. Thank u for finding out the error in the coding. If u have solved the prob pl send me the corresponding code to me, as i am in great need of it
thanks, bye
hi guys,
I found a way to solve the problem of Format Exception on RECEIVER side. It was probably due to the contents of FILE SIZE mixing with the CONTENT of the FILE. It is due to not allowing sufficient delay in transporting the FILESIZE & THE CONTENT OF FILE.
So insert a MessageBox("are you sure you want to send the file"), on the SENDER side after the line notifying "SENDING FILE ....."
cool
Hey all,
Without a few glitches here and there the program/tutorial is fine.Now, the name of the article is "File transfers through networks and the INTERNET". Has any1 tried to send files over the internet(not just LAN). I did and got an error(Exception).
If any of you know any links where i can get/see some code that does the file transfer correctly over the internet please let me know.
Thanks.
has anyone solved trappers problem as I have the same issue with the tutorial
has anyone solved trappers problem as I have the same issue with the tutorial and the "delay" did not fix it
Sir this has helped me a lot but , i am getting confuse at the point where i have to send the file to the seperate clients ..and also deciding the folder to store the file at run time (as here c:\).. so please help me out for this ..
thanks ..
Hi all.
I'm new to the sharp so my solution is... stupid, but for now its the only one :D
Don't use file size... at the client - comment (//):
strRemote.Write(ByteFileSize, 0, ByteFileSize.Length);
Then at the server side, comment:
bytesSize = strRemote.Read(downBuffer, 0, 2048);
And:
long FileSize = Convert.ToInt64(System.Text.Encoding.ASCII.GetString(downBuffer, 0, bytesSize));
Then remove all FileSize and its done.
It works fine to me :)
Here's a better way to fix trappers problem:
We use two helper functions, one on the server side and the other on the client side {client side uses byteEncode(), while the server side uses returnValue()}
private static byte[] byteEncode(string s, int size)
{
byte[] b = new byte[size];
byte[] c = System.Text.Encoding.ASCII.GetBytes(s.ToCharArray());
for (int k = 0; k < c.Length; k )
b[k] = c[k];
//Console.WriteLine("" (char)b[0] (char)b[1]);
try
{
for (int i = s.Length; i < size; i )
b[i] = (byte)'*';
}
catch (Exception) { }
return b;
}
private static string returnValue(byte[] arr)
{
int idx = -1;
for (int i = 0; i < arr.Length; i )
{
if (arr[i] == '*')
{
idx = i;
break;
}
}
string strBuilder = "";
for (int j = 0; j < idx; j )
strBuilder = arr[j];
return strBuilder;
}
What this does is it fills up the remaining bytes, which is 2048-something with '*'s. The other side rejects those '*'s and takes the other stuff out. Then you can do with it as you like.
Also note that to decode it on the server side, you would need to use an instance of the MemoryStream class. For example (on the server side):
MemoryStream memstream = new MemoryStream();
byte[] byteData = new byte[2048];
int bytesRead = strRemote.Read(byteData, 0, byteData.Length);
memstream.Write(byteData, 0, bytesRead);
Then by using "memstream.GetBuffer()", we can get the desired byte array to be used for the returnValue() method.
Lastly, we shall update the bytesRead variable:
bytesRead = strRemote.Read(byteData, 0, byteData.Length);
For some reason the returnValue() function copied incorrectly:
Here's a slight tweak (the correct version):
private static string returnValue(byte[] arr)
{
int idx = -1;
for (int i = 0; i < arr.Length; i )
{
if (arr[i] == '*')
{
idx = i;
break;
}
}
string strBuilder = "";
for (int j = 0; j < idx; j )
strBuilder = (char)arr[j];
return strBuilder;
}
How exactly may the above code be implemented? ie how do I use the value returned by memstream.GetBuffer? Also, where should I put
MemoryStream memstream = new MemoryStream();
byte[] byteData = new byte[2048];
int bytesRead = strRemote.Read(byteData, 0, byteData.Length);
memstream.Write(byteData, 0, bytesRead);
? I assume within the StartListening() method.
I have traded to keep to you but still there are lots of plases thet I dont undestend pless could you upload the sample project.
Hey Valerijs
I have this from quite some time back. Not sure if this works perfectly, but this should be at least 95% working. It'll help for sure if you debug it and go through it.
Download the file at:
http://hrishank.weebly.com/attachments-miscellaneous-work.html
There's only one file on that page called: "ftpuploadmodule.zip". It's a Visual Studio 2008 project.
Andrew,
Thank you for the wonderful code.
I do have one question, I'm trying to send two files one after another to same connection like
send.SendFile("sample-1.m2v");
send.SendFile("sample-2.m2v");
And the first file is received ok, while the name of the second file gets mixed with content so it looks like
FileName: sample-2.m2v\0\0[]?\f\x....MPEG-1, 25 frames/sec\0\0...
Do you know what this might be?
Thank you
As a part of the application which m making..i want to calculate the total data transfer between particular interval of time..ie the total amont of download n uploaded data..by the user..cn any1 provide me with d code to calculate the total data transfer in asp.net for web application
Related Tutorials
Related Source Code
C# Job Search