Newbie: Sending file over a network stream

  • Thread starter Thread starter abdul bari
  • Start date Start date
A

abdul bari

Hi Will the following code adequately send a file over a tcp
connection. Or is there something fundamentaly wrong with it? And does
any one know any good tutorials on sending files over tcp. What is the
simplest way of extracting the file at the server end?
thanks abz

TcpClient tcpclient = new TcpClient();

try {

tcpclient.Connect("127.0.0.1",8000); //use IPaddress as in the server

Console.WriteLine("Connected to server");
NetworkStream stm = tcpclient.GetStream();
if(stm.CanWrite && stm.CanRead){
//do write
FileInfo fi = new FileInfo("file.xml");
long total = fi.Length ;
long rdby=0;
bool check =true ;
int i=0;

//FileStreams to the file to be Uploaded
//when uploading file should be locked to other processes

FileStream fin = fi.Open(FileMode.Open,FileAccess.ReadWrite,FileShare.None);
byte[] reader = new byte[4096];
//Loop till the File is totaly read
while(rdby<total&&check){
//Read from the File
i = fin.Read(reader,0,reader.Length) ;
//Send the Bytes to the Server
stm.Write(reader,0,reader.Length);
rdby=rdby+i ;
}
Console.WriteLine("Finished sending file");
fin.Close();
}

else if (!stm.CanRead){
Console.WriteLine("You cannot write to this stream");
tcpclient.Close();
}
tcpclient.Close();

}
 
Back
Top