c# 局域網文件傳輸實例


 

一個基於c#的點對點局域網文件傳輸小案例,運行效果截圖

//界面窗體

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 文件傳輸
{
public partial class Form1 : Form
{
/// <summary>
/// 文件名
/// </summary>
private string fileName;
/// <summary>
/// 文件路徑
/// </summary>
private string filePath;
/// <summary>
/// 文件大小
/// </summary>
private long fileSize;
public Form1()
{
InitializeComponent();
Thread.CurrentThread.IsBackground=true;
textBox2.Text = IpUtil.GetLocalIp();
label1.Text = "您的ip:" + IpUtil.GetLocalIp() + " 您的端口:" + IpUtil.GetRandomPort();
var s= new FileRecive(this);
new Thread(s.run).Start();
}

/// <summary>
/// 信息提示框
/// </summary>
/// <param name="msg"></param>
public void Tip(string msg) {

MessageBox.Show(msg,"溫馨提示");
}

/// <summary>
/// 發送文件
/// </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("請選擇文件");
return;
}
if(ip.Length==0||port.ToString().Length==0){

Tip("端口和ip地址是必須的!");
return;
}

var c = new FileSend(this,new string[]{ip,port,fileName,filePath,fileSize.ToString()});
new Thread(c.Send).Start();
}

/// <summary>
/// 選擇文件
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog dig = new OpenFileDialog();

dig.ShowDialog();

//獲取文件名
this.fileName = dig.SafeFileName;

//獲取文件路徑
this.filePath = dig.FileName;

FileInfo f = new FileInfo(this.filePath);

//獲取文件大小
this.fileSize = f.Length;
textBox1.Text = filePath;
}

/// <summary>
/// 更新進度條
/// </summary>
/// <param name="value"></param>
public void UpDateProgress(int value) {


this.progressBar1.Value=value;
this.label2.Text = value + "%";
System.Windows.Forms.Application.DoEvents();
}

/// <summary>
/// 修改狀態
/// </summary>
/// <param name="state"></param>
public void SetState(string state) {

label5.Text = state;
}
/// <summary>
/// 退出程序
/// </summary>
public void Exit() {

Application.Exit();
}
}
}

//ip和端口工具類

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

namespace 文件傳輸
{
class IpUtil
{
/// <summary>
/// 獲取本地ip地址
/// </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>
/// 產生隨機端口
/// </summary>
/// <returns></returns>
public static int GetRandomPort() {


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

//文件發送類

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

namespace 文件傳輸
{

//文件發送類
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
{
//連接接收端
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);
//對方要接收我發送的文件
if (msg.Equals("1"))
{

fm.SetState("正在發送:");
FileStream os = new FileStream(param[3], FileMode.OpenOrCreate);

data = new byte[1024];
//記錄當前發送進度
long currentprogress = 0;
len=0;
while ((len = os.Read(data, 0, data.Length)) > 0) {
currentprogress += len;
//更新進度條
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("發送成功!");
fm.Exit();
}
}
}
catch (Exception e)
{

fm.Tip(e.Message);

}

}
}
}

 

//文件接收類

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 文件傳輸
{

/// <summary>
/// 文件接收類
/// </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>
/// 接收文件
/// </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() + "給您發了一個文件:" + tip[0] + "大小為:" + (long.Parse(tip[1]) / 1024) + "kb ,確定要接收嗎?", "接收提醒", MessageBoxButtons.YesNo))
{

//將接收信息反饋給發送方
msg = "1";
msgs = Encoding.UTF8.GetBytes(msg);
this.stream.Write(msgs, 0, msgs.Length);
this.stream.Flush();
fm.SetState("正在接收:");
//開始接收文件
string path = @"C:\Users\Administrator\Desktop\" + tip[0];//接收文件的存儲路徑
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;
//更新進度條
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("成功接收文件並存入了" + path + "中!");
fm.Exit();

}

}
catch (Exception e)
{
fm.Tip(e.Message);

}
}
}
}
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM