Getting issue while downloading file from blob storage - c#

Hi i have to download a 5 to 6 GB file from blob storage, on downloading i am getting the below mentioned error each time.
Error-:
Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
My code for downloading:
protected void btn_download_Click1(object sender, EventArgs e)
{
AccountFileTransfer = CloudStorageAccount.Parse("DefaultEndpointsProtocol=http;AccountName=" + ACCOUNTNAME + ";AccountKey=" + ACCOUNTKEY);
if (AccountFileTransfer != null)
{
BlobClientFileTransfer = AccountFileTransfer.CreateCloudBlobClient();
ContainerFileTransfer = BlobClientFileTransfer.GetContainerReference(CONTAINER);
ContainerFileTransfer.CreateIfNotExist();
BlobRequestOptions options = new BlobRequestOptions();
options.Timeout = new TimeSpan(0, 180, 0);
}
var blob = ContainerFileTransfer.GetBlockBlobReference(downloadfile);
var sasUrl = blob.Uri.AbsoluteUri;
CloudBlockBlob blockBlob = new CloudBlockBlob(sasUrl);
//blobSize = Convert.ToInt32(lblfilesize.Text.ToString());
blockSize = 5 * 1024*1024;
Response.Clear();
Response.ContentType = "APPLICATION/OCTET-STREAM";
System.String disHeader = "Attachment; Filename=\"" + blockBlob.Name + "\"";
Response.AppendHeader("Content-Disposition", disHeader);
for ( offset = 0; offset < blobSize; offset += blockSize)
{
using (var blobStream = blockBlob.OpenRead())
{
if ((offset + blockSize) > blobSize)
{
blockSize =(blobSize - offset);
}
byte[] buffer = new byte[blockSize];
blobStream.Read(buffer, 0, buffer.Length);
Response.BinaryWrite(buffer);
Response.Flush();
}
}
Response.End();
}

Related

Upload PDF file to host with WPF C#

How can I upload a PDF file to host via C# so that it is available for download via an adroid app? This is what I have tried, but it does not work. What am I doing wrong?
static void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
string fileName = ((FTPsetting)e.Argument).Filename;
string fullName = ((FTPsetting)e.Argument).FullName;
string username = ((FTPsetting)e.Argument).Username;
string password = ((FTPsetting)e.Argument).Password;
string server = ((FTPsetting)e.Argument).Server;
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}/{1}", server, fileName)));
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(username, password);
Stream ftpstream = request.GetRequestStream();
FileStream fs = File.OpenRead(fullName);
byte[] buffer = new byte[1024];
double total = (double)fs.Length;
int byteread = 0;
double read = 0;
do
{
if (!backgroundWorker.CancellationPending)
{
byteread = fs.Read(buffer, 0, 1024);
ftpstream.Write(buffer, 0, byteread);
read += (double)byteread;
double percontage = read / total * 100;
backgroundWorker.ReportProgress((int)percontage);
}
}
while (byteread != 0);
fs.Close();
ftpstream.Close();
}
static void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
Console.WriteLine("Completed" + e.ProgressPercentage + "%");
}

memory out of exception in windows phone

I am using Lumia 640 for development.
I got an memory out of exception in windows phone 8.1 Silver Light Application.
I have tried to dispose stream, remove bitmap from memory but still facing this issues.
When collecting More than 5 Images using CameraCaptureTask it will throws "memory out of exception".
I am posing My Demo Code Here.
private void Button_Click(object sender, RoutedEventArgs e)
{
CameraCaptureTask cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Show();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(this.CameraCaptureTaskCompleted);
}
private async void CameraCaptureTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
Debug.WriteLine("[ApplicationCurrentMemoryUsage](MB) : \n" + (DeviceStatus.ApplicationCurrentMemoryUsage / 1024 / 1024));
Image attachedImage = new Image();
Stream fileStream = e.ChosenPhoto;
string strFolderName = "Capture";
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
var fileName = Guid.NewGuid() + ".JPG";
if (!isf.DirectoryExists(strFolderName))
{
isf.CreateDirectory(strFolderName);
}
if (isf.FileExists(strFolderName + "\\" + fileName))
{
isf.DeleteFile(strFolderName + "\\" + fileName);
}
IsolatedStorageFileStream isfs = isf.CreateFile(strFolderName + "\\" + fileName);
int bytesRead = 0;
var bufferSize = Convert.ToInt32(fileStream.Length);
var fileBytes = new byte[fileStream.Length];
while ((bytesRead = await fileStream.ReadAsync(fileBytes, 0, bufferSize)) > 0)
{
isfs.Write(fileBytes, 0, bytesRead);
}
BitmapImage bitImage = new BitmapImage();
bitImage.SetSource(fileStream);
bitImage.DecodePixelType = DecodePixelType.Physical;
bitImage.CreateOptions = BitmapCreateOptions.BackgroundCreation;
bitImage.CreateOptions = BitmapCreateOptions.DelayCreation;
double dblRation = (double)bitImage.PixelWidth / bitImage.PixelHeight;
//if (bitImage.PixelWidth > bitImage.PixelHeight)
//{
// bitImage.DecodePixelWidth = 200;
// bitImage.DecodePixelHeight = 200 / (int)dblRation;
//}
//else
//{
// bitImage.DecodePixelHeight = 200;
// bitImage.DecodePixelWidth = (int)(200 * dblRation);
//}
attachedImage.Source = bitImage;
GC.Collect();
GC.WaitForPendingFinalizers();
fileStream.Flush();
fileStream.Dispose();
fileStream.Close();
bitImage = null;
fileStream = null;
fileBytes = null;
sp.Children.Add(attachedImage);
Debug.WriteLine("[ApplicationCurrentMemoryUsage](MB) : \n" + (DeviceStatus.ApplicationCurrentMemoryUsage / 1024 / 1024));
}
}
It is just demo code. When I pick first image it will rise from 8 MB to 37 MB usage.But in real application it will rise from 64 MB to 112 MB.
Please help me to sort it out.

Uri encoding, file download doesn't work with , and whitespace

I have an asp.net webpage that allows downloading files.
When i had the problem of downloading a file with whitespace(Test 1 4 3.txt) it will turn the file into: Test+1+4+3.txt
I used:
_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
And it solved the issue.
Now i have a new issue:
When a file contains , it changes it into %2c and i the UrlEncode doesn't fix it.
i Tried using:
_Response.AddHeader("Content-Disposition", "attachment;filename=" + Uri.EscapeDataString(_fileName));
But it's the old setting and it doesn't support whitespace.
What can i do to solve such a case?
Should i use regex / switch?
This is my function:
public static bool ResponseFile(HttpRequest _Request, HttpResponse _Response, string _fileName, string _fullPath, long _speed = 1024000)
{
try
{
FileStream myFile = new FileStream(_fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
_Response.AddHeader("Accept-Ranges", "bytes");
_Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
int pack = 10240; //10K bytes
int sleep = (int)Math.Floor((double)(1000 * pack / _speed)) + 1;
if (_Request.Headers["Range"] != null)
{
_Response.StatusCode = 206;
string[] range = _Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
_Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
_Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
_Response.AddHeader("Connection", "Keep-Alive");
_Response.ContentType = "application/octet-stream";
//Old didn't work with both + and ,
//_Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(_fileName, System.Text.Encoding.UTF8));
_Response.AddHeader("Content-Disposition", "attachment;filename=" + Uri.EscapeDataString(_fileName));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (_Response.IsClientConnected)
{
_Response.BinaryWrite(br.ReadBytes(pack));
Thread.Sleep(sleep);
}
else
{
i = maxCount;
}
}
}
catch
{
return false;
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
return false;
}
return true;
}
This solved it:
_Response.AddHeader("Content-Disposition", "attachment;filename=\"" + _fileName + "\"");

Download function failing with big file sizes

Hi my download function.
protected void downloadFunction(string fileName)
{
string filePath = #"D:\SoftwareFiles\";
LogMessageToFile("Download started " + filePath + fileName);
byte[] array = File.ReadAllBytes(filePath + fileName);
Response.Clear();
Response.ContentType = "application/x-newton-compatible-pkg";
Response.AppendHeader("Content-Disposition",
"attachment;filename=" + fileName);
Response.BinaryWrite(array);
Response.End();
}
When handling filesize of 20, 200mb no problem.
When handling 1gb file, an exception is thrown:
Overflow or underflow in the arithmetic operation.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArithmeticException: Overflow or underflow in the arithmetic operation.
What to do?
My guess is that you're running out of memory in the byte[] array.
You can try breaking the file down and reading it in chunks.
I found a code example from a Google search to get you started:
C# file downloader AKA Response.BinaryWrite
using System;
using System.IO;
using System.Web;
public class Download
{
public static void SmallFile(string filename, string filepath, string contentType)
{
try
{
FileStream MyFileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
long FileSize;
FileSize = MyFileStream.Length;
byte[] Buffer = new byte[(int)FileSize];
MyFileStream.Read(Buffer, 0, (int)MyFileStream.Length);
MyFileStream.Close();
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
HttpContext.Current.Response.BinaryWrite(Buffer);
}
catch
{
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Downloading Error!");
}
HttpContext.Current.Response.End();
}
public static void LargeFile(string filename, string filepath, string contentType)
{
Stream iStream = null;
// Buffer to read 10K bytes in chunk
//byte[] buffer = new Byte[10000];
// Buffer to read 1024K bytes in chunk
byte[] buffer = new Byte[1048576];
// Length of the file:
int length;
// Total bytes to read:
long dataToRead;
try
{
// Open the file.
iStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
// Total bytes to read:
dataToRead = iStream.Length;
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
// Read the bytes.
while (dataToRead > 0)
{
// Verify that the client is connected.
if (HttpContext.Current.Response.IsClientConnected)
{
// Read the data in buffer.
length = iStream.Read(buffer, 0, 10000);
// Write the data to the current output stream.
HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
// Flush the data to the HTML output.
HttpContext.Current.Response.Flush();
buffer = new Byte[10000];
dataToRead = dataToRead - length;
}
else
{
//prevent infinite loop if user disconnects
dataToRead = -1;
}
}
}
catch (Exception ex)
{
// Trap the error, if any.
//HttpContext.Current.Response.Write("Error : " + ex.Message);
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
finally
{
if (iStream != null)
{
//Close the file.
iStream.Close();
}
HttpContext.Current.Response.End();
HttpContext.Current.Response.Close();
}
}
public static void ResumableFile(string filename, string fullpath, string contentType)
{
try
{
FileStream myFile = new FileStream(fullpath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
BinaryReader br = new BinaryReader(myFile);
try
{
HttpContext.Current.Response.AddHeader("Accept-Ranges", "bytes");
HttpContext.Current.Response.Buffer = false;
long fileLength = myFile.Length;
long startBytes = 0;
//int pack = 10240; //10K bytes
int pack = 1048576; //1024K bytes
if (HttpContext.Current.Request.Headers["Range"] != null)
{
HttpContext.Current.Response.StatusCode = 206;
string[] range = HttpContext.Current.Request.Headers["Range"].Split(new char[] { '=', '-' });
startBytes = Convert.ToInt64(range[1]);
}
HttpContext.Current.Response.AddHeader("Content-Length", (fileLength - startBytes).ToString());
if (startBytes != 0)
{
HttpContext.Current.Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, fileLength - 1, fileLength));
}
HttpContext.Current.Response.AddHeader("Connection", "Keep-Alive");
HttpContext.Current.Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8));
br.BaseStream.Seek(startBytes, SeekOrigin.Begin);
int maxCount = (int)Math.Floor((double)((fileLength - startBytes) / pack)) + 1;
for (int i = 0; i < maxCount; i++)
{
if (HttpContext.Current.Response.IsClientConnected)
{
HttpContext.Current.Response.BinaryWrite(br.ReadBytes(pack));
}
else
{
i = maxCount;
}
}
}
catch
{
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
finally
{
br.Close();
myFile.Close();
}
}
catch
{
HttpContext.Current.Response.ContentType = "text/html";
HttpContext.Current.Response.Write("Error : file not found");
}
}
}

Can't download word document, throwing exception

I'm using response object to download word document which is stored in database as a content. It is throwing the following exception :
SubStatusCode 'Response.SubStatusCode' threw an exception of type 'System.PlatformNotSupportedException'
base {"This operation requires IIS integrated pipeline mode."} System.NotSupportedException {System.PlatformNotSupportedException}
Headers 'Response.Headers' threw an exception of type 'System.PlatformNotSupportedException'
I cannot able to view my file.. My code is as follows:
protected void btnResumedload_Click(object sender, EventArgs e)
{
DataTable dtResumeInfo = new DataTable();
dtResumeInfo = bc.ConvertByteToDataTable(objservice.getResumeInfo(int.Parse(Session["LoginId"].ToString())));
if (dtResumeInfo.Rows.Count > 0)
{
string doctype = dtResumeInfo.Rows[0]["ContentType"].ToString();
string docname = dtResumeInfo.Rows[0]["FileName"].ToString();
//
try
{
Response.Buffer = false;
Response.ClearHeaders();
Response.ContentType = doctype;
Response.AddHeader("Content-Disposition",
"attachment; filename=" + docname);
//
//Code for streaming the object while writing
const int ChunkSize = 1024;
byte[] buffer = new byte[ChunkSize];
byte[] binary = (dtResumeInfo.Rows[0]["ContentData"]) as byte[];
MemoryStream ms = new MemoryStream(binary);
int SizeToWrite = ChunkSize;
for (int i = 0; i < binary.GetUpperBound(0) - 1; i = i + ChunkSize)
{
if (!Response.IsClientConnected) return;
if (i + ChunkSize >= binary.Length)
SizeToWrite = binary.Length - i;
byte[] chunk = new byte[SizeToWrite];
ms.Read(chunk, 0, SizeToWrite);
Response.BinaryWrite(chunk);
Response.Flush();
}
Response.Close();
}
catch (Exception ex)
{
lblmsg.Visible = true;
lblmsg.Text = ex.Message;
}
}
else
{
lblmsg.Visible = true;
lblmsg.Text = "No Resume Information Found.";
}
}
It appears as though you are using the Response.Headers property which is only supported by the IIS 7.0 integrated pipeline mode. See: IIS6 + HttpModule: This operation requires IIS integrated pipeline mode

Categories

Resources