//请求文件 private void listView_file_DoubleClick(object sender, EventArgs e) { if (listView_file.SelectedItems.Count == 0) { return; } ListViewItem lv_item = listView_file.SelectedItems[0]; int index = lv_item.Index; applying_file = fileInfo_list[index]; if (host_flag) { byte[] file_info; if (!host_file_list.TryGetValue(applying_file, out file_info)) { MessageBox.Show("没有找到文件!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } string savePath; string file_suffix = applying_file.name.Substring(applying_file.name.LastIndexOf('.')); SaveFileDialog save_file_Dialog = new SaveFileDialog() { Filter = "(*" + file_suffix + ")|*" + file_suffix + "", FileName = applying_file.name }; if (save_file_Dialog.ShowDialog(this) == DialogResult.OK) { savePath = save_file_Dialog.FileName; using (FileStream fs = new FileStream(savePath, FileMode.Append, FileAccess.Write)) { fs.Write(file_info, 0, file_info.Length); fs.Flush(); fs.Close(); } add_msg2list("系统消息:", "请求的文件已经保存:" + savePath, Color.Red); } } else { host_connectNC.Send_message_NumString(5, applying_file.length.ToString() + '_' + applying_file.name); add_msg2list("系统消息", "正在下载文件:" + applying_file.name, Color.Red); } }
//发送文件 private void button_file_Click(object sender, EventArgs e) { if (openFileDialog1.ShowDialog() == DialogResult.OK) { string file_name = openFileDialog1.SafeFileName; //文件名 string file_path = openFileDialog1.FileName; //文件全路径 long file_length = new FileInfo(file_path).Length; //以字节为单位 if (file_length > 100 * 1000 * 1000) //超过100M { MessageBox.Show("文件大小不能超过100M", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } else if (file_length <= 0) { MessageBox.Show("文件为空!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } Sock_connected.Send_message_NumString(3, file_name); add_msg2list("系统消息", "正在发送文件:" + file_path, Color.Red); byte[] buffer_Chat_send = new byte[1024 * 1024 * 110];//110M缓存 using (FileStream fs = new FileStream(file_path, FileMode.Open, FileAccess.Read)) { int readLength = 0; //bool firstRead = true; //long sentFileLength = 0; readLength = fs.Read(buffer_Chat_send, 0, buffer_Chat_send.Length); Sock_connected.Send_message_NumByte(2, buffer_Chat_send, readLength); /*while ((readLength = fs.Read(buffer_Chat_send, 0, buffer_Chat_send.Length)) > 0 && sentFileLength < file_length) * { * sentFileLength += readLength; * * //第一次发送的字节流上加前缀 * if (firstRead) * { * //第一个字节标记2,代表为文件 * Sock_connected.Send_message_NumByte(2, buffer_Chat_send, readLength); * firstRead = false; * } * Sock_connected.sock.Send(buffer_Chat_send, 0, readLength, SocketFlags.None); * }*/ fs.Close(); } } }