C # File Transfer

Source: Internet
Author: User

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 ");

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.