在我的服務器程序中,我應該從客戶端取一個文件,但這可以是任意大小,所以我怎麼才能知道它的大小,以便我可以爲它設置緩衝區大小。我試過這個代碼,但最後我只是得到1kb文件夾,這是不工作了。尋找傳入文件的大小
private void checkRequest()
{ // Checks if request is a download or upload request and calls function that fits.
...
...
...
else if (Request.Contains("Upload")) //If request is upload (Client wants to upload)
{
info = Request;
nickName = Request.Substring(0, Request.IndexOf("Upload")); //Takes nickname
info = info.Replace(nickName, ""); //Takes nickName of the client and deletes
info = info.Replace("Upload", ""); //Deletes request.
if (!sList.Contains(nickName)) //If nick name is unique
{
info = info.Substring(0, info.IndexOf("end"));
sList.Add(nickName); //Adds nick name into a list.
Receive(info);
}
}
else
{
serverSocket.Close(); // If any problem occurs server becomes offline.
}
}
private void Receive(string receivedFileName)
{
byte[] buffer = new byte[1024]; //This is the part I can't fit anything.
activity.AppendText("File downloading to " + fileDir + " destination");
while (tempSocket.Receive(buffer) != 0)
{
File.WriteAllBytes(fileDir + "//" + fileName, buffer); //Creates a new file or overwrites it.
}
activity.AppendText("File downloaded..."); // Updates activity log(text box.)
}
'tempSocket.Receive(緩衝)'不garunteed經常閱讀'buffer.Length'字節,你需要檢查從'Receive'的結果,只使用很多'buffer'中的字節。同樣來自[WriteAllBytes]上的MSDN(http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes%28v=vs.110%29.aspx)「*創建一個新文件,將指定的字節數組寫入文件,然後關閉該文件。**如果目標文件已經存在,它將被覆蓋**。*「,您需要使用附加內容而不是覆蓋文件。 –