public void UploadFile(RemoteFileInfo request) { // Console will display the file and the size of the transfer Console.WriteLine("Start uploading " + request.FileName); Console.WriteLine("Size " + request.Length); // create output folder, if does not exist if (!Directory.Exists(request.userPath)) Directory.CreateDirectory(request.userPath); // delete target file, if already exists string filePath = Path.Combine(request.userPath, request.FileName); if (File.Exists(filePath)) File.Delete(filePath); int chunkSize = 2048; byte[] buffer = new byte[chunkSize]; using (FileStream writeStream = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write)) { do { // read bytes from input stream int bytesRead = request.FileByteStream.Read(buffer, 0, chunkSize); if (bytesRead == 0) break; // write bytes to output stream writeStream.Write(buffer, 0, bytesRead); } while (true); Console.WriteLine("Done!"); writeStream.Close(); } }
public RemoteFileInfo DownloadFile(DownloadRequest request) { //get the username path and the filename string filePath = Path.Combine(request.userPath, request.FileName); FileInfo fileInfo = new FileInfo(filePath); // Console will display the file and the size of the transfer Console.WriteLine("Sending stream " + request.FileName + " to client"); Console.WriteLine("Size " + fileInfo.Length); // checks to see if it exists if (!fileInfo.Exists) throw new FileNotFoundException("File not found", request.FileName); // opens up stream FileStream stream = new FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); // return result RemoteFileInfo result = new RemoteFileInfo(); result.FileName = request.FileName; result.Length = fileInfo.Length; result.FileByteStream = stream; result.userPath = request.userPath; return result; // after returning to the client download starts. Stream remains open and on server and the client reads it, although the execution of this method is completed. }