Here is a routine you can use to build the packet that the client will send to the server. The first sizeof(int) bytes will contain the length of the file in bytes that you are sending. Immediately after those bytes will begin the actual file data. Now since TCP is a byte stream protocol, and it guarantees that the bytes you send will arrive in order, on the server side we can peek until there are sizeof(int) bytes in the receive buffer. Once we have those bytes we know the length of the file. After that we can just call some other routine to block on a read of the socket until it reads those total number of bytes from the stream. After that simply return your array of bytes and use it for whatever you want on the server.
Code:
static byte[] GetFileBuffer(string FileName)
{
if (!File.Exists(FileName))
throw new FileNotFoundException("Could Not Find " + FileName);
using (MemoryStream ms = new MemoryStream())
{
using (BinaryWriter br = new BinaryWriter(ms))
{
FileInfo Info = new FileInfo(FileName);
br.Write((int)Info.Length);
br.Write(File.ReadAllBytes(FileName));
//The stream expands as you add bytes, make sure the final buffer
//is the specified size.
ms.Capacity = (int)Info.Length + sizeof(int);
return ms.GetBuffer();
}
}
}
Note the using blocks are just syntactic sugar for calling the dispose method from the IDispose interfaces that those classes implement. This insures that any resources that the objects used will be disposed of (and in many cases also surpresses the GC from performing a finalize on the object for extra efficiency).