I need to share a large file between two UWP apps which are running in two different machines using stream sockets. In order to share the file successfully, I have to share file size before sharing the actual file. So I had to set a separate event in separate page to share the file size. Otherwise, the shared file is corrupted and can't open.
I have provided related code for server and client below.
Server - First Page
private async void init_Click (object sender, RoutedEventArgs e) {
byte[] byteArray;
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile zipFile = await localFolder.GetFileAsync (App.fileName);
await Frame.Dispatcher.RunAsync (CoreDispatcherPriority.Normal, async () => {
using (Stream stream = await zipFile.OpenStreamForReadAsync ()) {
using (var memoryStream = new MemoryStream ()) {
stream.CopyTo (memoryStream);
byteArray = memoryStream.ToArray ();
}
}
StreamWriter streamWriter = new StreamWriter (App.outputStream);
await streamWriter.WriteLineAsync (byteArray.Length.ToString ());
await streamWriter.FlushAsync ();
await App.outputStream.FlushAsync ();
});
}
Second Page
private async void ShareVideo_Click (object sender, RoutedEventArgs e) {
byte[] byteArray;
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile zipFile = await localFolder.GetFileAsync (App.fileName);
await Frame.Dispatcher.RunAsync (CoreDispatcherPriority.Normal, async () => {
using (Stream stream = await zipFile.OpenStreamForReadAsync ()) {
using (var memoryStream = new MemoryStream ()) {
stream.CopyTo (memoryStream);
byteArray = memoryStream.ToArray ();
}
}
App.outputStream.Write (byteArray, 0, byteArray.Length);
await App.outputStream.FlushAsync ();
});
}
Client
private async void Page_Loaded (object sender, RoutedEventArgs e) {
if (App.clientSocket != null) {
StreamReader streamReader = new StreamReader (App.inputStream);
string size = await streamReader.ReadLineAsync ();
if (size != null) {
App.fileSize = Convert.ToInt32 (size);
byte[] buffer = new byte[App.fileSize];
await App.inputStream.ReadAsync (buffer, 0, App.fileSize);
string copiedFileName = "test.zip";
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile file = await localFolder.CreateFileAsync (copiedFileName, CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync (file, buffer);
await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync (CoreDispatcherPriority.Normal, async () => {
MessageDialog successMsg = new MessageDialog ("Shared zip file.");
successMsg.Title = "Success Message";
IAsyncOperation show = successMsg.ShowAsync ();
await Task.Delay (TimeSpan.FromSeconds (1));
show.Cancel ();
});
}
}
}
When I send file size and actual file in one event, it sets file size correctly on the client-side even though file sharing gets corrupted.
How can I send file size and actual data from one event to share the file successfully? Any idea on this is much appreciated.
Thanks