示例#1
0
        private void btnDownloadFile_Click(object sender, EventArgs e)
        {
            if (lvFiles.SelectedItems.Count == 0)
            {
                return;
            }

            string localFilePath = "";
            string localFileName = lvFiles.SelectedItems[0].Text;
            int    blockSize     = 2048;

            CryptoServiceClient cloudProxy = new CryptoServiceClient();

            Stream inputStream   = cloudProxy.DownloadFile(ref localFileName);
            string fileExtension = Path.GetExtension(localFileName);


            using (SaveFileDialog sf = new SaveFileDialog())
            {
                sf.FileName = localFileName;
                sf.Filter   = "(*" + fileExtension + ")|" + fileExtension;
                if (sf.ShowDialog() == DialogResult.OK)
                {
                    localFilePath = sf.FileName;
                }
                else
                {
                    return;
                }
            }

            using (FileStream writeStream = new FileStream(localFilePath, FileMode.Create, FileAccess.Write))
            {
                byte[] buffer = new byte[blockSize];

                do
                {
                    var bytesRead = inputStream.Read(buffer, 0, buffer.Length);

                    if (bytesRead == 0)
                    {
                        break;
                    }

                    //Then it's last block
                    if (bytesRead < blockSize)
                    {
                        var temp = new byte[bytesRead];
                        Array.Copy(buffer, temp, bytesRead);
                        buffer = temp;
                    }

                    writeStream.Write(buffer, 0, buffer.Length);
                } while (true);

                writeStream.Close();
            }

            if (File.Exists(localFilePath))
            {
                MessageBox.Show("File downloaded.", "Downloaded successfull", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Error while downloading file.", "Downloading error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            inputStream.Dispose();

            cloudProxy.Close();
        }