Today, I finally learned about file transfer. I sent this code to help people who are learning it.
Send:
Code
String Path = "E: \ C # \ convey_file \ form1.cs"; // file to be transmitted
Tcpclient client = new tcpclient ();
Client. Connect (IPaddress. parse ("192.168.0.52"), 9999 );
Filestream file = new filestream (path, filemode. Open, fileaccess. Read); // note the difference between filestream and receive.
Binaryreader = new binaryreader (File );
Byte [] B = new byte [4098];
Int data;
Console. writeline ("sending files ");
While (Data = binaryreader. Read (B, 0, 4098 ))! = 0) // note that the file is written as a stream.
{
Client. Client. Send (B, Data, socketflags. None); // send the file to the target machine.
}
Client. Client. Shutdown (socketshutdown. Both );
Binaryreader. Close ();
File. Close ();
Code
Receive:
Code
Private socket S;
Tcplistener TL;
Public void Lis ()
{
String Path = "d :\\ 1.cs"; // path of the file to be imported
TL = new tcplistener (9999 );
TL. Start ();
Console. writeline ("waiting for acceptance ");
S = tl. acceptsocket ();
Filestream FS = new filestream (path, filemode. openorcreate, fileaccess. Write); // note that this attribute is different from that of the send end.
Binarywriter binarywrite = new binarywriter (FS );
Int count;
Byte [] B = new byte [4098];
While (COUNT = S. Receive (B, 4098, socketflags. None ))! = 0) // This is to accept the file stream
{
Binarywrite. Write (B, 0, count); // write the received stream as a file
}
Binarywrite. Close ();
FS. Close ();
S. Close ();
TL. Stop ();
Console. writeline ("file transfer completed ");