private void SendFile(string fileName) { FileInfo f = new FileInfo(fileName); string md5 = PUtility.CalculateMD5(fileName); FileMeta fileMeta = new FileMeta( f.Length, fileName, md5); fileMeta.Type = (int)PacketType.FileMeta; Packet.Serialize(fileMeta).CopyTo(this.sendBuf, 0); this.Send(); Recv(); ACK ack = (ACK)Packet.Deserialize(this.recvBuf); if (ack.isOK == false) { // same name file ack = new ACK(false); if (MessageBox.Show("A same name already exists.\r\n\r\n" + "Do you want version control?", "FM", MessageBoxButtons.YesNo) == DialogResult.Yes) { ack.isOK = true; } Packet.Serialize(ack).CopyTo(this.sendBuf, 0); this.Send(); } if (f.Length != 0) { byte[] file = File.ReadAllBytes(fileName); this.stream.Write(file, 0, file.Length); this.stream.Flush(); } Recv(); ack = (ACK)Packet.Deserialize(this.recvBuf); if (ack.isOK) { //MessageBox.Show("성공적으로 업로드하였습니다!"); } else { MessageBox.Show("파일 업로드 실패"); } }
private void HandleFileMeta() { FileMeta fileMeta = (FileMeta)Packet.Deserialize(this.recvBuf); this.Invoke(new MethodInvoker(delegate() { txtLog.AppendText("File Name : " + fileMeta.fileName + "\r\n"); txtLog.AppendText("File Hash : " + fileMeta.md5Hash + "\r\n"); })); ACK ack = new ACK(); ack.Type = (int)PacketType.ACK; if (File.Exists(pathCur + Path.GetFileName(fileMeta.fileName))) { ack.isOK = false; Packet.Serialize(ack).CopyTo(this.sendBuf, 0); this.Send(); Recv(); ack = (ACK)Packet.Deserialize(this.recvBuf); if (ack.isOK == true) { // version try { PUtility.CompressWithVersion(pathCur + Path.GetFileName(fileMeta.fileName)); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } else { Packet.Serialize(ack).CopyTo(this.sendBuf, 0); this.Send(); } FileStream fs = File.Open(pathCur + Path.GetFileName(fileMeta.fileName), FileMode.Create); BinaryWriter writer = new BinaryWriter(fs); int nRecv = 0; long nRemain = fileMeta.fileLength; byte[] buff = new byte[PUtility.BUF_LEN]; try { if (fileMeta.fileLength != 0) { while ((nRecv = stream.Read(buff, 0, buff.Length)) > 0) { writer.Write(buff, 0, nRecv); writer.Flush(); nRemain -= nRecv; if (nRemain <= 0) { break; } } } } catch { ACK ackFail = new ACK(false); ackFail.Type = (int)PacketType.ACK; Packet.Serialize(ackFail).CopyTo(this.sendBuf, 0); this.Send(); } finally { writer.Close(); fs.Close(); } string md5 = PUtility.CalculateMD5(pathCur + Path.GetFileName(fileMeta.fileName)); if (String.Compare(md5, fileMeta.md5Hash) == 0) { ACK ackSuc = new ACK(); ackSuc.Type = (int)PacketType.ACK; Packet.Serialize(ackSuc).CopyTo(this.sendBuf, 0); this.Send(); File.WriteAllText(pathCur + Path.GetFileNameWithoutExtension(fileMeta.fileName) + ".gpg", md5); } else { ACK ackFail = new ACK(false); ackFail.Type = (int)PacketType.ACK; Packet.Serialize(ackFail).CopyTo(this.sendBuf, 0); this.Send(); } }