在我的服务器程序中,我应该从客户端取一个文件,但这可以是任意大小,所以我怎么才能知道它的大小,以便我可以为它设置缓冲区大小。我试过这个代码,但最后我只是得到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)“*创建一个新文件,将指定的字节数组写入文件,然后关闭该文件。**如果目标文件已经存在,它将被覆盖**。*“,您需要使用附加内容而不是覆盖文件。 –