Reputation: 383
I am passing an argument to my method wherein the datatype of this is string, but this string is a binary type "UEsDBBQABgAIAAAAIQDfz5sukgEAAJQGAAATANwBW0NvbnRlbnRfVHlwZ" for example, then this parameter will then be written into an excel format. The problem is, the file can be created but is corrupted due to invalid format. The input parameter comes from an excel file but is read as binary.
My sample code is:
public void writeFile(String fileContent)
{
// Write the string to a file.
StreamWriter file = new StreamWriter("c:\\test2.xlsx");
BinaryWriter bw = new BinaryWriter(file);
bw.Write(fileContent);
bw.Close();
file.Close();
}
Thanks.
Upvotes: 0
Views: 2251
Reputation: 5524
if bytes are coming as string use code as follows:
var base64EncodedBytes = System.Convert.FromBase64String(bytesAsString);
File.WriteAllBytes(fullPath, base64EncodedBytes);
Hope this helps.
Upvotes: 0
Reputation: 66641
Binary data can not be send or use them as text/string as is, and the reason is that that there are binary numbers that you can not represent them with text characters - at the same time some binary numbers have different meaning in a string.
What you can do is to convert it to string using one of
and then convert it back to binary
The asp.net have all ready the Convert.ToBase64String
and Convert.FromBase64String
to make the convert.
The convert functions from asp.net:
http://msdn.microsoft.com/en-us/library/dhx0d524.aspx
http://msdn.microsoft.com/en-us/library/system.convert.frombase64string.aspx
a custom convert example
http://www.csharp411.com/convert-binary-to-base64-string/
Upvotes: 5