![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public sealed class SocketData 2 { 3 private SocketData() 4 { 5 } 6 7 public static SendFileMode SendFile(Socket socket, string fileName, int maxBufferLength) 8 { 9 SendFileMode flag = SendFileMode.Success; 10 try 11 { 12 using (Stream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read)) 13 { 14 long fileLength = fs.Length; 15 long leftLength = fileLength; 16 int readLength = 0; 17 byte[] buffer = null; 18 var file_name = System.IO.Path.GetFileName(fileName); 19 var bytefileName = System.Text.Encoding.UTF8.GetBytes(file_name + "|" + fs.Length); 20 socket.Send(bytefileName); 21 if (fileLength <= maxBufferLength) 22 { /* 文件可以一次读取*/ 23 buffer = new byte[fileLength]; 24 readLength = fs.Read(buffer, 0, (int)fileLength); 25 //开始发送 26 socket.Send(buffer, SocketFlags.None); 27 } 28 else 29 { 30 while (leftLength != 0) 31 { 32 if (leftLength < maxBufferLength) 33 { 34 buffer = new byte[leftLength]; 35 readLength = fs.Read(buffer, 0, Convert.ToInt32(leftLength)); 36 } 37 else 38 { 39 buffer = new byte[maxBufferLength]; 40 readLength = fs.Read(buffer, 0, maxBufferLength); 41 } 42 //开始发送 43 socket.Send(buffer, SocketFlags.None); 44 leftLength -= readLength; 45 } 46 } 47 } 48 } 49 catch (IOException) 50 { 51 52 flag = SendFileMode.IOException; 53 } 54 return flag; 55 } 56 }
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 public enum SendFileMode 2 { 3 IOException = -4, 4 TimeOut = -1, 5 Success = 0, 6 SendFileError = -2, 7 SocketException=-3 8 }