public void SendFile(string remoteHostIP, int remoteHostPort, string longFileName, string shortFileName)
{
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortFileName);
byte[] fileData = File.ReadAllBytes(longFileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
TcpClient clientSocket = new TcpClient(remoteHostIP, remoteHostPort);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(clientData, 0, clientData.GetLength(0));
networkStream.Close();
}
可以使用此函數發送1GB文件,因爲我現在嘗試發送的最大文件大小隻有最多400MB。更多的是會導致'System.OutOfMemoryException'錯誤。 當我使用另一種方法將文件拆分成幾個部分,但服務器端不能連續接收部分,只能接收其中一個部分。C#如何使用TCP客戶端發送1GB文件
private void splitBigFile(string FileInputPath, byte[] inputArray)
{
int port = 1113;
double partSize = 104852000;
int partSize2 = 104852000;
string FolderOutputPath = "C:\\Users\\xx\\Desktop\\testing split";
string currPartPath;
string shortNameSplit;
FileStream fileStream = new FileStream(FileInputPath, FileMode.Open);
FileInfo fiSource = new FileInfo(txtFile.Text);
double sourceLength = fiSource.Length;
partNum = (int)Math.Ceiling((double)(sourceLength/partSize));
for (int i = 0; i < partNum; i++)
{
if (i == (partNum - 1))
{
partSize2 = (int)fiSource.Length - (i * 104852000);
}
currPartPath = FolderOutputPath + "\\" + fiSource.Name + "." + String.Format(@"{0:D4}", i) + ".part";
shortNameSplit = fiSource.Name + "." + String.Format(@"{0:D4}", i) + ".part";
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortNameSplit);
byte[] readStream = new byte[partSize2];
byte[] concateFile = new byte[5 + fileNameByte.Length];
int ipSend = ((partNum - 1 - i) << 1);
ipSend |= 0; // for differentiate ip or file
byte[] byteSend = new byte[1];
byteSend[0] = (byte)ipSend;
fileStream.Read(readStream, 0, partSize2);
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
byteSend.CopyTo(concateFile, 0);
fileNameLen.CopyTo(concateFile, 1);
fileNameByte.CopyTo(concateFile, 5);
concateFile.CopyTo(inputArray, 0);
readStream.CopyTo(inputArray, concateFile.Length);
string ipAddress = "192.168.43.67";
int sendport = 1113;
//Task.Factory.StartNew(() => SendBigFileSize(ipAddress, sendport, inputArray[i]));
Array.Clear(readStream, 0, readStream.Length);
Array.Clear(fileNameLen, 0, fileNameLen.Length);
Array.Clear(fileNameByte, 0, fileNameByte.Length);
Array.Clear(byteSend, 0, byteSend.Length);
Array.Clear(byteSend, 0, byteSend.Length);
}
fileStream.Close();
}
一次一個塊.. –
但我嘗試了許多方式,我分裂的文件的一部分,在接收端只能接收一次,雖然客戶端仍然繼續發送。 – ht9876
我沒有看到你嘗試任何方式。 – Blindy