Fix this is not a valid bitmap file - c#

string sDir = #"\\Q1875G\Vehicle";
NetworkCredential NCredentials = new NetworkCredential("FOLDER_ACCESS_USER", "Welcome#2020");
using (new NetworkConnection(sDir, NCredentials))
{
string path = $"{sDir}\\483";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileName = "add_274400.jpg";
path = $"{sDir}\\483\\{fileName}";
byte[] byteArrayIn = imageByteArray;
using (var ms = new MemoryStream(byteArrayIn))
{
using (var fs = new FileStream(path, FileMode.Create))
{
ms.WriteTo(fs);
}
}
}
Using this code image file getting created but when I try to open it, it gives an error that this is not a valid bitmap file, or its format is not currently supported.

That's not a JPEG yet; it's the bytes of a jpeg, base64 encoded, and prefixed with a header that would make it suitable for plonking inline into an <img src= tag attribute
The jpeg data starts with the /9j so you'll have to do something like:
var b64jpeg = Encoding.ASCII.GetString(imageByteArray, 23, imageByteArray.Length - 23);
var jpegBytes = Convert.FromBase64String(b64jpeg);
Then write jpegBytes to a file. There is no need to put it in a MemoryStream first; just File.WriteAllBytes it
If this imageByteArray has been delivered to you as a string (outside the code visible in the question) it would be better to keep it as that and substring it, rather than having this "to array (in the other code), from array (in this code)" step
Side note: you don't need if (!Directory.Exists(path)) either; Directory.CreateDirectory does nothing if the directory exists, so just call it without the Exists check

Related

Streamed File Contains Strange Characters - An Encoding Issue

I have a WCF service end-point which generates an excel file and returns this file as a MemoryStream in the end in order to make client download the relevant file.
The file generated on the respective directory has no issues. I don't see any strange characters when I open and check it.
But, the file I returned with MemoryStream is full of strange unreadable characters.
My end-point is like that,
public Stream GetEngagementFeedFinalizeData(int workspaceId, string startDate, string endDate, Stream data)
{
try
{
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;";
string extension = "xls";
string fileName = "report-" + DateTime.Now.Ticks.ToString();
string contentDisposition = string.Format(CultureInfo.InvariantCulture, "attachment; filename={0}.{1}", fileName, extension);
WebOperationContext.Current.OutgoingResponse.ContentType = contentType;
WebOperationContext.Current.OutgoingResponse.Headers.Set("Content-Disposition", contentDisposition);
//Here is some business logic and fetching data from db. Not any encoding
//related issue. The data set is assigned to a variable
//named "feedFinalizeDataTable" in the end
feedFinalizeDataTable.TableName = "Summary";
DataSet dataSet = new DataSet();
dataSet.Tables.Add(feedFinalizeDataTable);
using (ExcelPackage excelPackage = new ExcelPackage())
{
foreach (DataTable dt in dataSet.Tables)
{
ExcelWorksheet sheet = excelPackage.Workbook.Worksheets.Add(dt.TableName);
sheet.Cells["A1"].LoadFromDataTable(dt, true);
}
var path = System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory);
var filePath = path + "\\" + "New.xls";
excelPackage.SaveAs(new System.IO.FileInfo(filePath)); //This file is flawless
FileStream fs = new FileStream(filePath, FileMode.Open);
int length = (int)fs.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
byte[] buffer = new byte[length];
int sum = 0;
int count;
while ((count = fs.Read(buffer, sum, length - sum)) > 0)
{
sum += count;
}
fs.Close();
return new MemoryStream(buffer); //This file is full of unreadable chars as per above shared screenshot
}
I'm using OfficeOpenXml to generate excel files.
Then, I checked both files encoding by open them with notepad. I saw that the file on the directory (the flawless one) has ANSI encoding. And, the one which is returned by the end-point (the broken one) has UTF-8 encoding.
After that, I try to change the encoding type of the stream like this,
var byteArray = System.IO.File.ReadAllBytes(filePath);
string fileStr = new StreamReader(new MemoryStream(byteArray), true).ReadToEnd();
var encd = Encoding.GetEncoding(1252); //On the other topics I saw that ANSI represented with 1252
var end = encd.GetBytes(fileStr);
return new MemoryStream(end);
But, this doesn't help too. Though some of the strange characters are replaced with some other strange characters, but as I said, streamed file is still unreadable. And, when I open it with notepad to see its encoding, I saw that its still UTF-8.
Thus, I'm kind of stuck. I have also try directly to stream the generated excel file (without writing it to a directory and then reading it) with OfficeOpenXml's built in function called .GetAsByteArray(), but the downloaded file looks exactly the same as per above screenshot.
Thanks in advance.

Copy and Paste files as a user

In my application there are some files. Which I want to be able to copy and paste elsewhere in application.
The file I want to copy and paste I have stored inside a function GetPartialExportString()
My Idea:
When User clicks on "Copy" I create one file somewhere on comp and store it inside new created file
When user clicks "Paste" I Read from the file I generated when I clicked copy and add it there.
MemoryStream destinationStream = new MemoryStream();
protected void CopyCommand()
{
var modelAsString = GetPartialExportString();
string fileName = "copy.xaml";
string targetPath = #"C:\Users\";
string destFile = System.IO.Path.Combine(targetPath, fileName);
//System.IO.Directory.CreateDirectory(targetPath);
// convert string to stream
byte[] byteArray = Encoding.UTF8.GetBytes(modelAsString);
MemoryStream readingStream = new MemoryStream(byteArray);
FileStream file = new FileStream(fileName, FileMode.Create, FileAccess.Write);
readingStream.WriteTo(file);
file.Close();
readingStream.Close();
readingStream.CopyTo(destinationStream);
File.WriteAllText(destFile, modelAsString);
}
protected void PasteCommand()
{
string importString = File.ReadAllText("d:\\temp.txt");
LoadUnitFromXamlString("d:\\temp.txt");
}
It does not work like this. New to this, if someone can help I would appreciate!
File routes are incorect at the moment. But even when they were normal it was not working!
You should avoid overriding Close() method of Stream class for MemoryStream/FileStream objects. Use Dispose() instead.
You should get all the work done by the stream objects first and then dispose them.
After you've copied the contents of readingStream object to file, you'll have to readjust the position of stream buffer to the beginning of the contents present in readingStream object so as to copy it successfully to destinationStream.
Modify your code snippet like this:
readingStream.WriteTo(file);
readingStream.Position = 0;
readingStream.CopyTo(destinationStream);
file.Dispose();
readingStream.Dispose();
File.WriteAllText(destFile, modelAsString);

Converting full path of Image to binary

firstly, yes I know it might be a duplicate question, but really, I have applied all possible answers but nothing worked.
What I want is to convert an image selected by the user to binary format, and I'm using asp.net/c# to do such method.
Look at my codes first to do this:
if (FileUpload1.HasFile)
{
pressNumberOfTimes++;
string strname = Path.GetFileName(FileUpload1.PostedFile.FileName);
lbl_homeCarouselAdd.ID = "lbl_homeCarouselAdd" + pressNumberOfTimes;
strDiv.Append(string.Format(strname) + ",");
FileUpload1.PostedFile.SaveAs(HttpContext.Current.Server.MapPath("~/upload/") + strname);
string fullImagePath = HttpContext.Current.Server.MapPath("~/upload/") + strname;
byte[] imgdata = File.ReadAllBytes(fullImagePath);
var a = String.Join(",", lbl_homeCarouselAdd.Text += strDiv.ToString());
from what I have seen from the answers in this website and others to convert image to binary is to use this code:
byte[] imgdata = File.ReadAllBytes(fullImagePath);
which I have used in my codes.
However, all I get is an empty value for the binary, while "fullImagePath" variable holds the full bath of the selected image.
I have also used the following method, but it gave me the same empty result:
public static byte[] ImageToBinary(string _path)
{
FileStream fS = new FileStream(_path, FileMode.Open, FileAccess.Read);
byte[] b = new byte[fS.Length];
fS.Read(b, 0, (int)fS.Length);
fS.Close();
return b;
}
For more info:
This is how my web form looks like
so, the user can upload an image and then click "save image" button in order to save the selected event, and here the website should convert the image to binary format.
Concerns:
Is it possible that "upload" folder in my "VS" project is not refreshed with the new selected image is the reason behind the empty value??
Is it possible that permissions among c:\ directory is causing such error?? because I'm working on a machine given by the company I work for, and I did face some issues before regarding this.
if(FileUpload1.HasFile)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string extension = Path.GetExtension(filename);
string contentType = FileUpload1.PostedFile.ContentType;
HttpPostedFile file = FileUpload1.PostedFile;
byte[] imgdata= new byte[file.ContentLength];
file.InputStream.Read(imgdata, 0, file.ContentLength);
}

How to get the ZIP file from Base64 string in Javascript?

I am trying to get the compressed ZIP file back in Javascript. I am able to convert the zip file into Base64 String format. (Zip file is in Server)
Here is my try (at Server Side)
System.IO.FileStream fs = new System.IO.FileStream(SourceFilePath + "Arc.zip", System.IO.FileMode.Open);
Byte[] zipAsBytes = new Byte[fs.Length];
fs.Read(zipAsBytes, 0, zipAsBytes.Length);
String base64String = System.Convert.ToBase64String(zipAsBytes, 0, zipAsBytes.Length);
fs.Close();
if (zipAsBytes.Length > 0)
{
_response.Status = "ZipFile";
_response.Result = base64String;
}
return _json.Serialize(_response);
This part of code returns the JSON data. This JSON data includes the Base64 string. Now what i want to do is to get the original zip file from Base64 string. I searched over the internet but not get the idea.
Is this achievable ?.
It is achievable. First you must convert the Base64 string to an Arraybuffer. Can be done with this function:
function base64ToBuffer(str){
str = window.atob(str); // creates a ASCII string
var buffer = new ArrayBuffer(str.length),
view = new Uint8Array(buffer);
for(var i = 0; i < str.length; i++){
view[i] = str.charCodeAt(i);
}
return buffer;
}
Then, using a library like JSZip, you can convert the ArrayBuffer to a Zip file and read its contents:
var buffer = base64ToBuffer(str);
var zip = new JSZip(buffer);
var fileContent = zip.file("someFileInZip.txt").asText();
JavaScript does not have that functionality.
Theoretically there can be some js library that does this, but it's size probably would be bigger than the original text file itself.
You can also enable gzip compression on your server, so that any output text gets compressed. Most of the browsers would then uncompress the data upon its arrival.

Read a file from Windows Phone 7

I have a folder called data/ in my project that contains txt files.
I configured Build Action to resources to all files.
I tried these different ways:
method 1
var resource = Application.GetResourceStream(new Uri(fName, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
Debug.WriteLine(streamReader.ReadToEnd());
method 2
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.txt");
method 3
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fName, FileMode.Open, isf)))
{
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine();
al.Add(line);
Debug.WriteLine(line);
}
}
}
Now, i tried different ways to read files without success, why?
Where is the problem?
What's wrong with these methods?
fName is the name of the file.
It's necessary the full path data/filename.txt? It's indifferent...
please help me with this stupid issue,
thanks.
Your 2nd & 3rd approaches are wrong. When you include a text file locally in your app, you can't refer it via the IS. Instead, use this function, it will return the file content if found else it will return "null". It works for me, hope it works for you.
Note, if the file is set as content, the filePath = "data/filename.txt" but if it is set as resource it should be referred like this filePath = "/ProjectName;component/data/filename.txt". That may be why your 1st approach might have failed.
private string ReadFile(string filePath)
{
//this verse is loaded for the first time so fill it from the text file
var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
StreamReader myStreamReader = new StreamReader(myFileStream);
//read the content here
return myStreamReader.ReadToEnd();
}
}
return "NULL";
}

Categories