C # LAN File transfer instance

Source: Internet
Author: User
Tags getstream

A C # based point-to-point local area Network File transfer small case, running effect

Interface form

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.IO;
Using System.Linq;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;
Using System.Windows.Forms;

Namespace File transfer
{
public partial class Form1:form
{
<summary>
Filename
</summary>
private string FileName;
<summary>
File path
</summary>
private string FilePath;
<summary>
File size
</summary>
Private long fileSize;
Public Form1 ()
{
InitializeComponent ();
Thread.currentthread.isbackground=true;
TextBox2.Text = Iputil.getlocalip ();
Label1. Text = "Your IP:" + iputil.getlocalip () + "Your port:" + iputil.getrandomport ();
var s= new filerecive (this);
New Thread (S.run). Start ();
}

<summary>
Informational alert Box
</summary>
<param name= "MSG" ></param>
public void Tip (String msg) {

MessageBox.Show (msg, "warm Tips");
}

<summary>
Send file
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Button2_Click (object sender, EventArgs e)
{
string ip = TextBox2.Text;
String Port =textbox3.text;

if (Filename.length = = 0) {

TIP ("Please select File");
Return
}
if (IP. length==0| | Port. ToString (). length==0) {

Tip ("Port and IP address is required!");
Return
}

var c = new Filesend (This,new string[]{ip,port,filename,filepath,filesize.tostring ()});
New Thread (C.send). Start ();
}

<summary>
Select File
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Button1_Click (object sender, EventArgs e)
{
OpenFileDialog dig = new OpenFileDialog ();

Dig. ShowDialog ();

Get file name
This.filename = dig. Safefilename;

Get file path
This.filepath = dig. FileName;

FileInfo f = new FileInfo (This.filepath);

Get File size
This.filesize = F.length;
TextBox1.Text = FilePath;
}

<summary>
Update progress bar
</summary>
<param name= "Value" ></param>
public void updateprogress (int value) {


This.progressbar1.value=value;
This.label2.Text = value + "%";
System.Windows.Forms.Application.DoEvents ();
}

<summary>
Modify Status
</summary>
<param name= "state" ></param>
public void SetState (string state) {

Label5. Text = State;
}
<summary>
Exit program
</summary>
public void Exit () {

Application.exit ();
}
}
}

IP and Port tool classes

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Net;
Using System.Text;
Using System.Threading.Tasks;

Namespace File transfer
{
Class Iputil
{
<summary>
Get local IP Address
</summary>
<returns></returns>
public static string Getlocalip ()
{
string hostname = Dns.gethostname ();
Iphostentry localhost = dns.gethostbyname (hostname);
IPAddress localaddr = localhost. ADDRESSLIST[0];
Return LOCALADDR. ToString ();
}

<summary>
Generate Random ports
</summary>
<returns></returns>
public static int Getrandomport () {


return new Random (). Next (1000) +5000;
}
}
}

File Send Class

Using System;
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading.Tasks;

Namespace File transfer
{

File Send Class
Class Filesend
{
Private TcpClient client;
Private NetworkStream stream;
Private string[] param;
Private Form1 FM;
Public Filesend (Form1 fm,params string[] param) {

This.param = param;
THIS.FM = FM;

}

public void Send ()
{

Try
{
Connect to the receiving end
This.client = new TcpClient (param[0], int. Parse (param[1]));
String msg = param[2] + "|" + param[4];
byte[] m = Encoding.UTF8.GetBytes (msg);

while (true) {
This.stream = This.client.GetStream ();
This.stream.Write (M, 0, M.length);
This.stream.Flush ();
byte[] data = new byte[1024];
int len = this.stream.Read (data, 0, data. Length);
msg = Encoding.UTF8.GetString (data, 0, Len);
The other person wants to receive the files I sent
if (Msg. Equals ("1"))
{

Fm. SetState ("Sending:");
FileStream OS = new FileStream (param[3], filemode.openorcreate);

data = new byte[1024];
Record Current Delivery progress
Long currentprogress = 0;
len=0;
while (len = os. Read (data, 0, data. Length)) > 0) {
Currentprogress + = Len;
Update progress bar
Fm. UpdateProgress ((int) (Currentprogress*100/long). Parse (Param[4]));
This.stream.Write (Data,0,len);

}
Os. Flush ();
This.stream.Flush ();
Os. Close ();
This.stream.Close ();
Fm. Tip ("Send success!");
Fm. Exit ();
}
}
}
catch (Exception e)
{

Fm. Tip (E.message);

}

}
}
}

File Receive Class

Using System;
Using System.Collections.Generic;
Using System.IO;
Using System.Linq;
Using System.Net;
Using System.Net.Sockets;
Using System.Text;
Using System.Threading;
Using System.Threading.Tasks;
Using System.Windows.Forms;

Namespace File transfer
{

<summary>
File Receive Class
</summary>
Class Filerecive
{

Private TcpListener server;
Private Form1 FM;
Private NetworkStream stream;
Public filerecive (Form1 FM) {
THIS.FM = FM;
Try
{
This.server = new TcpListener (Ipaddress.parse (Iputil.getlocalip ()), Iputil.getrandomport ());

Server. Start ();
}
catch (Exception e) {

Fm. Tip (E.message);

}
}

<summary>
Receiving files
</summary>
public void Run ()
{


while (true)
{
Try
{
TcpClient client = server. AcceptTcpClient ();
This.stream = client. GetStream ();
byte[] msgs = new byte[1024];

int len = this.stream.Read (msgs, 0, Msgs. Length);

String msg = Encoding.UTF8.GetString (msgs, 0, Len);

String[] tip = Msg. Split (' | ');
if (Dialogresult.yes = = MessageBox.Show (iputil.getlocalip () + "sends you a file:" + tip[0] + "size:" + (Long). Parse (tip[1])/1024x768) + "KB, OK to receive?", "Receive reminders", Messageboxbuttons.yesno)
{

Feedback the received information to the sender
msg = "1";
Msgs = Encoding.UTF8.GetBytes (msg);
This.stream.Write (msgs, 0, Msgs. Length);
This.stream.Flush ();
Fm. SetState ("receiving:");
Start receiving files
string path = @ "C:\Users\Administrator\Desktop\" + tip[0];//the storage path of the received file
FileStream OS = new FileStream (path, filemode.openorcreate);

byte[] data = new byte[1024];
Long currentprogress = 0;
int length = 0;
while (length = this.stream.Read (data, 0, data. Length)) > 0)
{
Currentprogress + = length;
Update progress bar
Fm. UpdateProgress ((int) (currentprogress * 100/long. Parse (tip[1]));
Os. Write (data, 0, length);

}
Os. Flush ();
This.stream.Flush ();
Os. Close ();
This.stream.Close ();
Fm. Tip ("successfully received the file and deposited in the" + Path + "!");
Fm. Exit ();

}

}
catch (Exception e)
{
Fm. Tip (E.message);

}
}
}
}
}

C # LAN File transfer instance

Related Article

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.