private void fileDownload(object sender, EventArgs e) { Button tileButton = (MetroTile)sender; var result = MessageBox.Show("해당 파일을 다운로드 하시겠습니까?", "파일 다운로드", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { SaveFileDialog fileDlg_save = new SaveFileDialog(); fileDlg_save.Title = "파일 저장"; fileDlg_save.FileName = tileButton.Name; fileDlg_save.Filter = "모든 파일(*.*)|*.*"; var fileDlgResult = fileDlg_save.ShowDialog(); if (fileDlgResult == DialogResult.OK) { this.fileDownloadForm = new FileDownloadForm(this.clientSocketWork, tileButton.Name, fileDlg_save.FileName, this); fileDownloadForm.ShowDialog(); MessageBox.Show("파일 다운로드가 완료되었습니다.", "파일 다운로드 완료", MessageBoxButtons.OK, MessageBoxIcon.Information); } } }
public void Receive(FileDownloadForm fileDownloadForm, Socket serverSocket, string newFilename) { byte[] receiveBuffer = new byte[4096]; byte[] fileSizeBuffer = new byte[4]; byte[] fileBuffer; byte[] temp; int receiveSize = 0; int fileSize = 0; int fileSizeSum = 0; int persent = 0; Console.WriteLine("im receving"); try { receiveSize = serverSocket.Receive(receiveBuffer); if (receiveSize > 0) { Buffer.BlockCopy(receiveBuffer, 0, fileSizeBuffer, 0, fileSizeBuffer.Length); fileSize = BitConverter.ToInt32(fileSizeBuffer, 0); fileBuffer = ByteMove(receiveBuffer, fileSizeBuffer.Length, receiveSize - (fileSizeBuffer.Length)); fileSizeSum = fileBuffer.Length; Console.WriteLine($"fileSize : {fileSize}, fileSizeSum : {fileSizeSum}"); while (fileSize > fileSizeSum) { receiveSize = serverSocket.Receive(receiveBuffer); fileSizeSum += receiveSize; if (fileSize != 0) { persent = (fileSizeSum * 100) / fileSize; } fileDownloadForm.Invoke((MethodInvoker) delegate { fileDownloadForm.UpdatePersent(persent); }); temp = new byte[receiveSize + fileBuffer.Length]; Buffer.BlockCopy(fileBuffer, 0, temp, 0, fileBuffer.Length); Buffer.BlockCopy(receiveBuffer, 0, temp, fileBuffer.Length, receiveSize); fileBuffer = temp; } Console.WriteLine($"fileSize : {fileSize}, fileSizeSum : {fileSizeSum}"); if (fileSize != fileSizeSum) { MessageBox.Show("파일이 손상되었습니다."); } using (FileStream fs = new FileStream(newFilename, FileMode.Create, FileAccess.Write)) { fs.Write(fileBuffer, 0, fileBuffer.Length); } Console.WriteLine("파일 생성 완료"); fileDownloadForm.Invoke((MethodInvoker) delegate { fileDownloadForm.Close(); }); } } catch (ArgumentException e) { Console.WriteLine(e.StackTrace); }catch (Exception e) { Console.WriteLine(e.StackTrace); } }