标签:
下面介绍一种最普通,方便的UDP文件传输方法。
将下面三步加入到你的程序通信部分就可以实现文件传输了!
第一步:选择传输文件
private void btnFileSend_Click(object sender, EventArgs e) { OpenFileDialog dlgOpenFile = new OpenFileDialog(); dlgOpenFile.ShowReadOnly = true; if (dlgOpenFile.ShowDialog() == DialogResult.OK) { try { string path = dlgOpenFile.FileName; fs = new FileStream(path, FileMode.Open, FileAccess.ReadWrite); SendMessage(ip, "FileName," + fs.Name ); } catch { MessageBox.Show("文件打开失败"); } } }第二步:接收文件函数
private void ReceiveMessage() { IPEndPoint remote = null;//远端任意主机,从任意端口发送信息 while (true) { try { byte[] bytes = receiveUdpClient.Receive(ref remote); string receive = Encoding.Unicode.GetString(bytes, 0, bytes.Length); string[] splitString = receive.Split(','); switch (splitString[0]) { case"FileName": if (MessageBox.Show("是否接收文件?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { FileStream fs1 = null; string[] file = splitString[1].Trim().Split('\\'); filePath = "C:\\" + file[file.Length-1]; fs1 = new FileStream(filePath, FileMode.Create); fs1.Close(); SendMessage(ip, "FileAgree"); } else { SendMessage(ip, "FileDeny"); } break; case "FileAgree": MessageBox.Show("开始发送文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question); FileRead(fs); break; case "FileDeny": MessageBox.Show("拒绝接收文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Question); fs.Close(); break; case "ACK": FileRead(fs); break; case "File": FileStream fs2 = null; fs2 = File.OpenWrite(filePath); fs2.Position = fs2.Length; //将待写入内容追加到文件末尾 byte[] bytes2 = Encoding.Unicode.GetBytes(splitString[2]); fs2.Write(bytes2, 0, bytes2.Length); fs2.Close(); SendMessage(ip, "ACK"); break; case "End":MessageBox.Show("接收成功"); break; } } catch { break; } } }第三步:文件读取函数
int fileSize = 1024; int count = 0; private void FileRead(FileStream temp) { byte[] bytes; if (fileSize >= temp.Length - count * fileSize) { bytes = new byte[temp.Length - count * fileSize]; int num = fs.Read(bytes, 0, bytes.Length); if (num != 0) SendMessage(ip, "File," + fs.Name + "," + Encoding.Unicode.GetString(bytes)); else { SendMessage(ip, "End,"); fs.Close(); count = 0; } } else { bytes = new byte[fileSize];//存储读取结果 int num = fs.Read(bytes, 0, bytes.Length); if (num != 0) { SendMessage(ip, "File," + fs.Name + "," + Encoding.Unicode.GetString(bytes)); count++; } } }
标签:
原文地址:http://blog.csdn.net/zlele0326/article/details/51334173