Download multiple file from blob as Zip folder - c#

My files are in blob storage.So how i can download the multiple files from folder as zip
I am trying this code from some time it is working but not giving me output.Means its not starting the zip download.:
string zipFileName = "MyZipFiles.zip";
using (var zipOutputStream = new
ZipOutputStream(HttpContext.Current.Response.OutputStream))
{
zipOutputStream.SetLevel(0);
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
HttpContext.Current.Response.ContentType = "application/zip";
foreach (var filePath in fileUrl)
{
var filename = Path.GetFileName(filePath.filename);
var filebytes = filePath.filebyte.BlobByteArray;
var fileEntry = new ZipEntry(Path.GetFileName(filePath.filename))
{
Size = filebytes.Length
};
zipOutputStream.PutNextEntry(fileEntry);
zipOutputStream.Write(filebytes, 0, filebytes.Length);
}
zipOutputStream.Flush();
zipOutputStream.Close();
}
My file url contains:
foreach (var item in obj)
{
em = new FileUrlForbyte();
em.filename = item.FileName;
em.url = objBlobHelper.GetFileByFileNameMultiple(item.ContainerName, item.SubFolderName + "/" + item.FileName, DateTime.Now.AddMinutes(2));
em.filebyte = objBlobHelper.DownloadFileByFileNameForAdobe(item.ContainerName, item.SubFolderName + "/" + item.FileName);
fileUrl.Add(em);
}
FOr more clarity:filePath contains:filename,fileurl and file byte:
[Route("api/Blob/getMultipleFileFromBlobByURI")]
[HttpGet]
public System.Web.Mvc.FileResult getMultipleFileFromBlobByURI(string containerName)
{
List<BlobStorageModel> obj = new JavaScriptSerializer().Deserialize<List<BlobStorageModel>>(containerName);
try
{
BlobHelper objBlobHelper = new BlobHelper(apiPrincipal);
List<FileUrlForbyte> fileUrl = new List<FileUrlForbyte>();
FileUrlForbyte em = new FileUrlForbyte();
foreach (var item in obj)
{
em = new FileUrlForbyte();
em.filename = item.FileName;
em.url = objBlobHelper.GetFileByFileNameMultiple(item.ContainerName, item.SubFolderName + "/" + item.FileName, DateTime.Now.AddMinutes(2));
em.filebyte = objBlobHelper.DownloadFileByFileNameForAdobe(item.ContainerName, item.SubFolderName + "/" + item.FileName);
fileUrl.Add(em);
}
// Here we will create zip file & download
string zipFileName = "MyZipFiles.zip";
var fileName = string.Format("{0}_ImageFiles.zip", DateTime.Today.Date.ToString("dd-MM-yyyy") + "_1");
var tempOutPutPath = System.Web.HttpContext.Current.Server.MapPath(Url.Content("/TempImages/")) + fileName;
try
{
using (var zipOutputStream = new ZipOutputStream(HttpContext.Current.Response.OutputStream))
{
zipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
HttpContext.Current.Response.BufferOutput = false;
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + zipFileName);
HttpContext.Current.Response.ContentType = "application/zip";
foreach (var filePath in fileUrl)
{
var filename = Path.GetFileName(filePath.filename);
var filebytes = filePath.filebyte.BlobByteArray;
var fileEntry = new ZipEntry(Path.GetFileName(filePath.filename))
{
Size = filebytes.Length
};
zipOutputStream.PutNextEntry(fileEntry);
zipOutputStream.Write(filebytes, 0, filebytes.Length);
}
zipOutputStream.Finish();
zipOutputStream.Flush();
zipOutputStream.Close();
}
byte[] finalResult = System.IO.File.ReadAllBytes(tempOutPutPath);
if (System.IO.File.Exists(tempOutPutPath))
System.IO.File.Delete(tempOutPutPath);
if (finalResult == null || !finalResult.Any())
throw new Exception(String.Format("No Files found with Image"));
return new System.IO.File(finalResult, "application/zip", fileName);
}
catch (Exception)
{
throw;
}
}
catch (Exception)
{
throw;
}
}

Thanks #Sudheer for your inputs in the comments.
I am trying this code from some time it is working but not giving me output.Means its not starting the zip download.: string zipFileName = “MyZipFiles.zip”;
Referring to the above comment I have tried the below code and was able to execute it successfully.
CloudStorageAccount storage_Account = CloudStorageAccount.Parse(storageAccount_connectionString);
CloudBlobClient blob_Client = storage_Account.CreateCloudBlobClient();
CloudBlobContainer container = blob_Client.GetContainerReference(container_Name);
CloudBlockBlob cloudBlockBlob = container.GetBlockBlobReference(filename);
Stream file = File.OpenWrite(#"C:\Tools\" + filename);
cloudBlockBlob.DownloadToStream(file);
Console.WriteLine("Download completed!");
Then, I have created a container in my storage account as shown below.
We need to upload the zip file into the above folder and run the given code.
Now I can see that I can access my container and download the zip file located inside the container.

Related

Download Files into a certain path in the internal Storage { C# Xamarin }

currently I am curious how to download files on your android device and save the file to a certain path on the INTERNAL STORAGE. My result I want to get at the end is: If the User click on a button it start to download and replace the file in the path that is defined.
Appreciate any help!
With my current code i tried to modify it directly, but had no success...
Wish y´all a Great Day & thanks for reading!
*Frost
Renegade = new Command(async () =>
{
string pak5 = "";
Stream stream1 = File.OpenRead(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal) + "Android/data/com.epicgames.fortnite/files/InstalledBundles/FortniteBR/FortniteGame/Content/Paks/pakchunk10_s5-Android_ASTCClient.ucas");
/*using (var streamWriter = new StreamWriter(pak5, true))
{
streamWriter.WriteLine(DateTime.UtcNow);
}
using (var streamReader = new StreamReader(pak5))
{
string content = streamReader.ReadToEnd();
System.Diagnostics.Debug.WriteLine(content);
}*/
StreamReader reader = new StreamReader(stream1);
string pakspath = reader.ReadToEnd();
//80000000
//80000000
//System.IO.File.Delete("/storage/emulated/0/Android/data/com.epicgames.fortnite/files/InstalledBundles/FortniteBR/FortniteGame/Content/Paks/pakchunk10_s5-Android_ASTCClient.ucas ");
//Utilities.Convert(Body, Body1, pakspath, 80000000);
//Utilities.Convert(Mat, Mat1, pakspath, 8981062);
ReplaceBytes(pakspath, 8981045, S1);
ReplaceBytes(pakspath, 8981045, S2);
ReplaceBytes(pakspath, 80782548, S3);
ReplaceBytes(pakspath, 80782548, S4);
ReplaceBytes(pakspath, 80782571, S5);
ReplaceBytes(pakspath, 80782571, S6);
});
If you are using Xamarin forms then ,Here is my solution.Make a class like this on your
Android project.
public class DroidFileHelper
{
public string GetLocalFilePath(string filename)
{
string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
return Path.Combine(path, filename);
}
public async Task SaveFileToDefaultLocation(string fileName, byte[] bytes, bool showFile = false)
{
Context currentContext = Android.App.Application.Context;
string directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
string file = Path.Combine(directory, fileName);
System.IO.File.WriteAllBytes(file, bytes);
//If you want to open up the file after download the use below code
if (showFile)
{
if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.N)
{
string externalStorageState = global::Android.OS.Environment.ExternalStorageState;
var externalPath = global::Android.OS.Environment.ExternalStorageDirectory.Path + "/" + global::Android.OS.Environment.DirectoryDownloads + "/" + fileName;
File.WriteAllBytes(externalPath, bytes);
Java.IO.File files = new Java.IO.File(externalPath);
files.SetReadable(true);
string application = "application/pdf";
Intent intent = new Intent(Intent.ActionView);
Android.Net.Uri uri = FileProvider.GetUriForFile(currentContext, "com.companyname.appname.provider", files);
intent.SetDataAndType(uri, application);
intent.SetFlags(ActivityFlags.GrantReadUriPermission);
Forms.Context.StartActivity(intent);
}
else
{
Intent promptInstall = new Intent(Intent.ActionView);
promptInstall.SetDataAndType(Android.Net.Uri.FromFile(new Java.IO.File(file)), "application/pdf");
promptInstall.SetFlags(ActivityFlags.NewTask);
Forms.Context.StartActivity(promptInstall);
}
}
}
}
after that call it like from your xamarin form.
Xamarin.Forms.DependencyService.Get<IFileHelper>().SaveFileToDefaultLocation(oFile.FileName, oFile.FileInBytes, true);
It will save your file to Downloads because we set the path as Android.OS.Environment.DirectoryDownloads in our droid helper class

Not able to download file. Giving Exception

I am trying to download multiple file in zip formate using zipOutputStream.
Its Giving Exception in blob.DownloadToStream(zipOutputStream); line
List<string> lstPath = DAL_AttachmentSQLHelper.GetAllAttachementPath(claimId);
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference("traveoappclaimattachments/Traveo1");
using (var zipOutputStream = new ZipOutputStream(System.Web.HttpContext.Current.Response.OutputStream))
{
foreach (var blobFileName in lstPath)
{
zipOutputStream.SetLevel(0);
var blob = container.GetBlockBlobReference(blobFileName);
var entry = new ZipEntry(blobFileName);
zipOutputStream.PutNextEntry(entry);
blob.DownloadToStream(zipOutputStream);
}
zipOutputStream.Finish();
zipOutputStream.Close();
}
System.Web.HttpContext.Current.Response.BufferOutput = false;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "zipFileName.zip");
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
One problem that I see with your code is how you're creating an instance of CloudBlobContainer in your code. Assuming your container name is traveoappclaimattachments and all the files are located in Traveo1, you could try something like below:
List<string> lstPath = DAL_AttachmentSQLHelper.GetAllAttachementPath(claimId);
CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
var container = cloudStorageAccount.CreateCloudBlobClient().GetContainerReference("traveoappclaimattachments");
using (var zipOutputStream = new ZipOutputStream(System.Web.HttpContext.Current.Response.OutputStream))
{
foreach (var blobFileName in lstPath)
{
zipOutputStream.SetLevel(0);
var blob = container.GetBlockBlobReference("Traveo1/" + blobFileName);
var entry = new ZipEntry(blobFileName);
zipOutputStream.PutNextEntry(entry);
blob.DownloadToStream(zipOutputStream);
}
zipOutputStream.Finish();
zipOutputStream.Close();
}
System.Web.HttpContext.Current.Response.BufferOutput = false;
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + "zipFileName.zip");
System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();

ZIP download is blocking because of organisation policy in asp.net

As am having my ZIP file in the folder and if I click download report button am blocking to download based on my organization policy.
But I need to download this ZIP file from the code how can we achieve this.
The code which I used as below
string[] filenames = Directory.GetFiles(SourceFolder);
ZipFilePath = DestinationFolder + #"\" + ZipFileName;
using (ZipOutputStream s = new
ZipOutputStream(File.Create(ZipFilePath)))
{
s.SetLevel(6);
byte[] buffer = new byte[4096];
foreach (string file in filenames)
{
if (Path.GetFileName(file).Contains(SubString) || Path.GetFileName(file).Contains("logfile"))
{
ZipEntry entry = new
ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0,
buffer.Length);
s.Write(buffer, 0, sourceBytes);
} while (sourceBytes > 0);
}
}
}
s.Finish();
s.Close();
}
string DownloadFileName = ZipFilePath;
DownloadFileName = DownloadFileName.Replace("\\", "~");
RadAjaxManager1.ResponseScripts.Add("setTimeout(function(){ document.location.href = 'DownloadHandler.ashx?FileName=" + DownloadFileName + "'; return false; },300);");
The DownloadHandler.ashx page as below
public void ProcessRequest(HttpContext context)
{
try
{
HttpResponse rspns = context.Response;
string FileToDownload = context.Request.QueryString["FileName"];
string FileName = string.Empty;
if (context.Request.QueryString["Name"] != null)
{
FileName = context.Request.QueryString["Name"];
}
if (FileToDownload!=null)
{
FileToDownload = FileToDownload.Replace("~", "\\");
FileName = System.IO.Path.GetFileName(FileToDownload);
}
else
{
//FileName = Convert.ToString(iTAPSession.UserData);
}
rspns.AppendHeader("content-disposition", "attachment; filename=\"" + FileName.Replace(" ", "%20"));
rspns.TransmitFile(FileToDownload);
rspns.End();
}
catch (Exception e)
{
}
}
public bool IsReusable
{
get
{
return false;
}
}
am getting the below exception
Based on your organization's access policies, access to this website or download ( http://xxxxxxx/ITAADemo/DownloadHandler.ashx?FileName=D:~ITAADemo~Files~SuperAdmin~bn4wgrusef1xgmjhqokd2yo2~~TextAnalytics~~zipdownload~Report_2018-Jul-19-11-39-31.zip ) has been blocked because the file type "application/zip" is not allowed.

C# No Data in Folder after Downloading ASP

Let me start off by saying I'm sure this is something that's quite simple, unfortunately I just can't seem to figure it out. So here's my problem, I query the database, return what I need, zip it all up, and prompt user to save. When You attempt to open this, there are no files inside the folder. Where has my data gone? I stepped through everything, and it appears to write everything properly. Any help would be greatly appreciated!!
if (e.CommandName == "DownloadAttachment")
{
e.Canceled = true;
// Create a zip and send it to the client.
//Response.Write(#"<script language='javascript'>alert('Details saved successfully')</script>");
var item = e.Item as GridEditableItem;
fileId = (int)item.GetDataKeyValue("Unique");
FileData[] allrecords = null;
using (
SqlConnection conn =
new SqlConnection(ConfigurationManager.ConnectionStrings["PtcDbModelEntities"].ConnectionString))
{
using (
SqlCommand comm = new SqlCommand("Select Unique1, BinaryData, FileName from PtcDbTracker.dbo.CafFileTable where Unique1=#fileId AND FileName IS NOT NULL", conn))
{
comm.Parameters.Add(new SqlParameter("#fileId", fileId));
conn.Open();
using (var reader = comm.ExecuteReader())
{
var list = new List<FileData>();
while (reader.Read())
{
list.Add(new FileData { Unique1 = reader.GetInt32(0) });
long len = reader.GetBytes(1, 0, null, 0, 0);
Byte[] buffer = new byte[len];
list.Add(new FileData { BinaryData = (byte)reader.GetBytes(1, 0, buffer, 0, (int)len), FileName = reader.GetString(2) });
allrecords = list.ToArray();
}
}
conn.Close();
}
}
using (var compressedFileStream = new MemoryStream())
{
//Create an archive and store the stream in memory.
using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false))
{
if (allrecords != null)
{
foreach (var record in allrecords)
{
//Create a zip entry for each attachment
if (record.FileName != null)
{
var zipEntry = zipArchive.CreateEntry(record.FileName);
//Get the stream of the attachment
using (var originalFileStream = new MemoryStream(record.BinaryData))
{
using (var zipEntryStream = zipEntry.Open())
{
//Copy the attachment stream to the zip entry stream
originalFileStream.CopyTo(zipEntryStream);
}
}
}
}
}
Response.ClearContent();
Response.ClearHeaders();
Response.BinaryWrite(compressedFileStream.ToArray());
Response.AppendHeader("Content-Disposition", "Attachment; filename=result.zip");
Response.Flush();
Response.Close();
zipArchive.Dispose();
//How Do I Prompt for open or save?
}
}
Are you sure the BinaryWrite is getting a valid ByteArray?
In any case here's a tested method to output a file to the Response with the typically needed headers for binary attachments:
public bool WriteFile(byte[] byteContent, DateTime dtTimeStamp, string urlFilename)
{
HttpContext context = HttpContext.Current;
HttpResponse response = context.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.BufferOutput = true;
response.AppendHeader("Content-Length", byteContent.Length.ToString());
response.AppendHeader("Content-Type", "application/octet-stream");
response.AppendHeader("Last-Modified", dtTimeStamp.ToString("R"));//Last-Modified Wed, 28 Aug 2013 10:16:46 GMT
response.AppendHeader("Content-Disposition", "inline; filename=\"" + urlFilename + "\"");
response.BinaryWrite(byteContent);
response.Flush();
// Prevents any other content from being sent to the browser
response.SuppressContent = true;
context.ApplicationInstance.CompleteRequest();
return true;
}

Images corrupting in FTP, Binary mode on

I made a post back in january about this, but it was never solved. I have been working on a program to ftp to my Youtube Teams website. For some odd reason, the HTML code generated works and is transferred successfully, but the images come through corrupted. I've made sure that Binary mode is set to true and permissions are all correct. Nothing seems to work.
Can somebody help me?
This is our part of the Code which is relevant to my question:
namespace TMNGP_FTP
{
partial class Form1
{
// some functions and properties for the form
UriBuilder ftpurl;
String ftpurlstr = "ftp://tmngp.heliohost.org";
static String ftpusername = "*******";
static String ftppassword = "*******";
public static string GenerateFileName(string context)
{
return context + DateTime.Now.ToString("yyyyMMddHHmmss") + ".html";
}
public void openpic_Click(object sender, System.EventArgs e)
{
//Wrap the creation of the OpenFileDialog instance in a using statement,
//Rather than manually calling the dispose method to ensure proper disposal
using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";
dlg.Filter = "png files (*.png)|*.png";
if (dlg.ShowDialog() == DialogResult.OK)
{
string folderName = #"c:\TMNGP_Web_Files";
string pathString = folderName + #"\htTemp";
pathString = pathString + #"\imgs";
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
}
string destFileName = pathString + #"\" + dlg.SafeFileName.ToString();
System.IO.File.Copy(dlg.FileName, destFileName, true);
DisplImg.Image = new Bitmap(dlg.OpenFile());
DisplImg.ImageLocation = destFileName;
}
}
}
private FtpClient ftpnew = null;
public void textgen_Click(object sender, System.EventArgs e)
{
string folderName = #"c:\TMNGP_Web_Files";
string pathString = folderName + #"\htTemp";
if (!System.IO.Directory.Exists(pathString))
{
System.IO.Directory.CreateDirectory(pathString);
}
string fileName = GenerateFileName("HT");
pathString = pathString + #"\" + fileName;
Console.WriteLine("Path to my file: {0}\n", pathString);
if (!System.IO.File.Exists(pathString))
{
//System.IO.FileStream fs = System.IO.File.Create(pathString);
using (System.IO.StreamWriter file = new System.IO.StreamWriter(pathString))
{
file.WriteLine("<div class='simple_overlay' id='news_archive/" + DisplImg.ImageLocation.Substring(31) + "' style='display:none;'>");
file.WriteLine("<a class='close'></a>");
file.WriteLine("<img src='news_archive/" + DisplImg.ImageLocation.Substring(31) + "'/>");
file.WriteLine("<div class='details'>");
file.WriteLine("<h3> " + txtTitle.Text + " </h3>");
file.WriteLine("<h4> " + TxtInfo.Text + " </h4>");
file.WriteLine("<p>" + Desctext.Text + "</p>");
file.WriteLine("</div>");
file.WriteLine("</div>");
}
if(radioButton1.Checked)
{
ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "NGP/news_archive/");
ftpurlstr = "/public_html/NGP/news_archive";
}
else
{
ftpurl = new UriBuilder("ftp", "tmngp.heliohost.org", 21, "TM/news_archive/");
ftpurlstr = "/public_html/TM/news_archive";
}
try
{
//string filenametwo = System.IO.Path.GetFullPath(#"c:\TMNGP_Web_Files\htTemp\"+fileName);
string filenamethree = System.IO.Path.GetFullPath(DisplImg.ImageLocation.ToString());
Console.WriteLine("{0}", filenamethree);
Console.WriteLine(pathString);
//string ftpfullpath = ftpurl;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create((#"ftp://tmngp.heliohost.org" + ftpurlstr + fileName).ToString());
Console.WriteLine("{0}", ftpurl + fileName);
ftp.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp.KeepAlive = true;
ftp.UseBinary = true;
ftp.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStreamone = new StreamReader(#"c:\TMNGP_Web_Files\htTemp\" + fileName);
byte[] fileContentsone = Encoding.UTF8.GetBytes(sourceStreamone.ReadToEnd());
sourceStreamone.Close();
ftp.ContentLength = fileContentsone.Length;
Stream requestStreamone = ftp.GetRequestStream();
requestStreamone.Write(fileContentsone, 0, fileContentsone.Length);
requestStreamone.Close();
FtpWebResponse ftpresponseone = (FtpWebResponse)ftp.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", ftpresponseone.StatusDescription);
ftpresponseone.Close();
}
catch (WebException ex)
{
throw ex;
}
try
{
string imgfile = DisplImg.ImageLocation.Substring(31);
FtpWebRequest ftp2 = (FtpWebRequest)FtpWebRequest.Create((#"ftp://tmngp.heliohost.org" + ftpurlstr + imgfile).ToString());
ftp2.Credentials = new NetworkCredential(ftpusername, ftppassword);
ftp2.KeepAlive = true;
ftp2.UseBinary = true;
ftp2.Method = WebRequestMethods.Ftp.UploadFile;
StreamReader sourceStreamtwo = new StreamReader(DisplImg.ImageLocation.ToString());
byte[] fileContentstwo = Encoding.UTF8.GetBytes(sourceStreamtwo.ReadToEnd());
sourceStreamtwo.Close();
ftp2.ContentLength = fileContentstwo.Length;
Stream requestStreamtwo = ftp2.GetRequestStream();
requestStreamtwo.Write(fileContentstwo, 0, fileContentstwo.Length);
requestStreamtwo.Close();
FtpWebResponse ftpresponsetwo = (FtpWebResponse)ftp2.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", ftpresponsetwo.StatusDescription);
ftpresponsetwo.Close();
}
catch (Exception ex)
{
throw ex;
}
MessageBox.Show("FTP Complete");
}
else
{
Console.WriteLine("File \"{0}\" already exists.", fileName);
return;
}
}
// a bunch of Windows Form Designer generated code ...
}
}
Ok this code is hard to read, BUT, it looks like you are using Encoding.UTF8.GetBytes() on the image (sourceStreamTwo) when you declare Byte[] fileContentTwo.
Edit - forgot to mention, you don't need the StreamReader - use a FileStream instead:
FileStream sourceStreamtwo = new FileStream(DisplImg.ImageLocation.ToString(), FileMode.Open);
Change that to
Byte[] fileContentTwo;
using (BinaryReader br = new BinaryReader(sourceStreamtwo))
{
fileContentsTwo = br.ReadBytes((int)sourceStreamtwo.Length);
// rest of code that deals with sourceStreamTwo
}
Note this assumes you aren't reading from a network where you might not have the whole stream available, see Creating a byte array from a stream
In .net 4 or higher you can use Stream.CopyTo() which is safer as it handles interruptions in the stream - again see above question and answers for more info.
And you should be good. Encoding is meant for text, images are binary.
Also please consider some different naming conventions for your variables :)

Categories

Resources