How to save byte[] in c# application settings - c#

I am trying to save a byte array (byte[]) in c# application settings that is returned by Object List View.
Can anyone give me a solution on how to save byte array in c# application settings?
or some trick on how to convert byte[] to something like a string then store, then retrieve and again convert it to byte array and give it back to object list view.

One of the most common ways to make a string from an array of bytes is encoding them in Base-64:
string encoded = System.Convert.ToBase64String(toEncodeAsBytes);
Use
byte[] bytes = System.Convert.FromBase64String(encoded);
to get your bytes back.

The canonical way to do this is to convert the byte[] to a string via base64 and the other way round.

By Different way you can convert Byte array to string and string to byte array. Like this :
1)
string asciiString = ASCIIEncoding.ASCII.GetString(byteArray);
byte[] byte = ASCIIEncoding.ASCII.GetBytes(asciiString);
2)
string base64String = System.Convert.ToBase64String(byteArray);
byte[] byte = System.Convert.FromBase64String(base64String);
3)
string utf8String = System.Text.Encoding.UTF8.GetString(byteArray);
byte[] byte = System.Text.Encoding.UTF8.GetBytes(utf8String);
you can also use System.Text.Encoding.BigEndianUnicode, System.Text.Encoding.Unicode, and System.Text.Encoding.UTF32 for converting Byte Array to string and string to Byte Array.
Hope, It should help you.

Related

Save byte array to SQLite database c#

please I can not solve it, some ideas? I see in DB only "System.Byte []" but no values from array.
Thank you.
Calling ToString() on a byte[] yields
System.Byte[]
But assuming that your byte[] contains a (UTF8 formatted) string, you could use
byte[] array= ...;
string myString = System.Text.Encoding.UTF8.GetString(array, 0, array.Length);
instead.

Storing png file as string

I have the following content stored as the value of a json element
When I open it in text visualizer, it appears like this
What happens to everything apart from PNG?
If this is something that string cannot hold, how can I make sure it holds the entire content? The reason I ask is I am trying to deserialize this to a C# object containing a string property but apparently that is null because of this junk content.
Do I need to encode/decode, or use UTF-8, or remove some special characters or something so that I can hold entire png content in a string variable?
png is a binary (non-text) file format. To embed that inside json, you should treat the value as either a byte[], or a string of an encoded form, such as base-64 or hexadecimal. Convert.ToBase64String will give you the base-64 from a byte[], but frankly I'd just hand your JSON serializer a byte[] and let it worry about it.
If you want to store binary data in JSON, base 64 is a good way to go:
Here's a sample of getting that string:
public string ImageToBase64(string path)
{
using(System.Drawing.Image image = System.Drawing.Image.FromFile(path))
{
using(MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
return Convert.ToBase64String(imageBytes);
}
}
}
Before you send the photo or a file, base64 encode them.
string myPhoto = Convert.ToBase64String(System.IO.File.ReadAllBytes(filepath));
Then to decode it
byte[] tempBytes = Convert.FromBase64String(PhotoString);

c# Convert.ToBase64(String) with no pluses

I have a string which I need to convert to base64.
The default convert
byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
return Convert.ToBase64String(cipherbytes);
I get a string which has '+' like "pURT+TFG=" and is converted to a space when sent as a get, so I can't compare to the original.
First, it sounds as a bad idea to send large sets of bytes in the query string. Short byte arrays should be fine. Make sure if this is what you need.
Second, you have to URL encode your base64 encoded string, by calling HttpUtility.UrlEncode or WebUtility.UrlEncode (prefer the latter):
byte[] cipherbytes = rsa.Encrypt(plainbytes, false);
return WebUtility.UrlEncode(Convert.ToBase64String(cipherbytes));

Bit Array to String and back to Bit Array

Possible Duplicate Converting byte array to string and back again in C#
I am using Huffman Coding for compression and decompression of some text from here
The code in there builds a huffman tree to use it for encoding and decoding. Everything works fine when I use the code directly.
For my situation, i need to get the compressed content, store it and decompress it when ever need.
The output from the encoder and the input to the decoder are BitArray.
When I tried convert this BitArray to String and back to BitArray and decode it using the following code, I get a weird answer.
Tree huffmanTree = new Tree();
huffmanTree.Build(input);
string input = Console.ReadLine();
BitArray encoded = huffmanTree.Encode(input);
// Print the bits
Console.Write("Encoded Bits: ");
foreach (bool bit in encoded)
{
Console.Write((bit ? 1 : 0) + "");
}
Console.WriteLine();
// Convert the bit array to bytes
Byte[] e = new Byte[(encoded.Length / 8 + (encoded.Length % 8 == 0 ? 0 : 1))];
encoded.CopyTo(e, 0);
// Convert the bytes to string
string output = Encoding.UTF8.GetString(e);
// Convert string back to bytes
e = new Byte[d.Length];
e = Encoding.UTF8.GetBytes(d);
// Convert bytes back to bit array
BitArray todecode = new BitArray(e);
string decoded = huffmanTree.Decode(todecode);
Console.WriteLine("Decoded: " + decoded);
Console.ReadLine();
The Output of Original code from the tutorial is:
The Output of My Code is:
Where am I wrong friends? Help me, Thanks in advance.
You cannot stuff arbitrary bytes into a string. That concept is just undefined. Conversions happen using Encoding.
string output = Encoding.UTF8.GetString(e);
e is just binary garbage at this point, it is not a UTF8 string. So calling UTF8 methods on it does not make sense.
Solution: Don't convert and back-convert to/from string. This does not round-trip. Why are you doing that in the first place? If you need a string use a round-trippable format like base-64 or base-85.
I'm pretty sure Encoding doesn't roundtrip - that is you can't encode an arbitrary sequence of bytes to a string, and then use the same Encoding to get bytes back and always expect them to be the same.
If you want to be able to roundtrip from your raw bytes to string and back to the same raw bytes, you'd need to use base64 encoding e.g.
http://blogs.microsoft.co.il/blogs/mneiter/archive/2009/03/22/how-to-encoding-and-decoding-base64-strings-in-c.aspx

C# ByteArray to string conversion and back

I have a uint value that I need to represent as a ByteArray and the convert in a string.
When I convert back the string to a byte array I found different values.
I'm using standard ASCII converter so I don't understand why I'm getting different values.
To be more clear this is what I'm doing:
byte[] bArray = BitConverter.GetBytes((uint)49694);
string test = System.Text.Encoding.ASCII.GetString(bArray);
byte[] result = Encoding.ASCII.GetBytes(test);
The bytearray result is different from the first one:
bArray ->
[0x00000000]: 0x1e
[0x00000001]: 0xc2
[0x00000002]: 0x00
[0x00000003]: 0x00
result ->
[0x00000000]: 0x1e
[0x00000001]: 0x3f
[0x00000002]: 0x00
[0x00000003]: 0x00
Notice that the byte 1 is different in the two arrays.
Thanks for your support.
Regards
string test = System.Text.Encoding.ASCII.GetString(bArray);
byte[] result = Encoding.ASCII.GetBytes(test);
Because raw data is not ASCII. Encoding.GetString is only meaningful if the data you are decoding is text data in that encoding. Anything else: you corrupt it. If you want to store a byte[] as a string, then base-n is necessary - typically base-64 because a: it is conveniently available (Convert.{To|From}Base64String), and b: you can fit it into ASCII, so you rarely hit code-page / encoding issues. For example:
byte[] bArray = BitConverter.GetBytes((uint)49694);
string test = Convert.ToBase64String(bArray); // "HsIAAA=="
byte[] result = Convert.FromBase64String(test);
Because c2 is not a valid ASCII char and it is replaced with '?'(3f)
Converting any byte array to string using SomeEncoding.GetString() is not a safe method as #activwerx suggested in comments. Instead use Convert.FromBase64String, Convert.ToBase64String

Categories

Resources