Hello,
Welcome to our Microsoft Q&A platform!
When you transfer a file, you can write the file size directly into the stream. It is recommended to use DataWriter as following:
writer = new DataWriter(socket.OutputStream);
// if we have a StorageFile named file
using (var stream=await file.OpenStreamForReadAsync())
using(var ms=new MemoryStream())
{
await stream.CopyToAsync(ms);
var bytes = ms.ToArray();
writer.WriteUInt32(Convert.ToUInt32(bytes.Length));
writer.WriteBytes(ms.ToArray());
await writer.StoreAsync();
}
The size of the incoming stream can be pre-read by the DataReader when receiving the file as following:
var reader = new DataReader(args.Socket.InputStream);
try
{
while (true)
{
//Read first 4 bytes(length of the subsequent string).
uint sizeFieldCount = await reader.LoadAsync(sizeof(uint));
if (sizeFieldCount != sizeof(uint))
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
// Read the string.
uint fileLength = reader.ReadUInt32();
uint actualFileLength = await reader.LoadAsync(fileLength);
if (fileLength != actualFileLength)
{
// The underlying socket was closed before we were able to read the whole data.
return;
}
var file =await ApplicationData.Current.LocalFolder.CreateFileAsync("test.zip", CreationCollisionOption.ReplaceIfExists);
var bytes =new byte[actualFileLength];
reader.ReadBytes(bytes);
await FileIO.WriteBytesAsync(file, bytes);
}
}
catch (Exception exception)
{
// If this is an unknown status it means that the error is fatal and retry will likely fail.
}
The above simple code that explains how to combine the file size with the actual content of the file. I hope it will help you.
Thanks