Пример #1
0
        /// <summary>
        /// Uploads a file that is passed as a stream.
        /// </summary>
        /// <param name="request">Stream of file for upload.</param>
        public void UploadFile(RemoteFileInfo request)
        {
            // report start
            Console.WriteLine("Start uploading " + request.FileName);
            Console.WriteLine("Size " + request.Length);

            // create output folder, if does not exist
            if (!Directory.Exists("Upload"))Directory.CreateDirectory("Upload");

            // kill target file, if already exists
            string filePath = Path.Combine("Upload", 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);

                // report end
                Console.WriteLine("Done!");
                // close stream at the end of reading
                writeStream.Close();
            }
        }
Пример #2
0
        /// <summary>
        /// Sends a stream for given requested file.
        /// </summary>
        /// <param name="request">File that will be downloaded from the service.</param>
        /// <returns></returns>
        public RemoteFileInfo DownloadFile(DownloadRequest request)
        {
            // get some info about the input file
            string filePath = Path.Combine("Upload", request.FileName);
            FileInfo fileInfo = new FileInfo(filePath);

            // report start
            Console.WriteLine("Sending stream " + request.FileName + " to client");
            Console.WriteLine("Size " + fileInfo.Length);

            // check if exists
            if (!fileInfo.Exists) throw new FileNotFoundException("File not found", request.FileName);

            // open stream
            FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);

            // return result
            RemoteFileInfo result = new RemoteFileInfo
            {
                FileName = request.FileName,
                Length = fileInfo.Length,
                FileByteStream = stream
            };
            // return file stream
            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.
        }