How to get an uncoded string from a base64 encoded gzipped text - c#-4.0

Text I am reading from a XML, which is suppose to be a string with base64 encoded and Gzip compressed. I am following the below steps:
string text = childNodes.Item(i).InnerText.Trim();
byte[] compressed = Convert.FromBase64String(text);
byte[] compressed = Convert.FromBase64String(text);
using (var uncompressed = new MemoryStream())
using (var inStream = new MemoryStream(compressed))
using (var outStream = new GZipStream(inStream, CompressionMode.Decompress))
{
outStream.CopyTo(uncompressed);
var reader = new StreamReader(uncompressed);
uncompressed.Position = 0;
string myStr = reader.ReadToEnd();
Console.WriteLine(myStr);
}
I am getting myStr value as something like :
�\b\0\0\0\0\0\0Ľk��ƒ �Y��ؘX{���z:�n�,ɏ�ek��xϞ�`�\0؍�|\t ��_3�\n(\0$�s.Cb�\0*3++��|
͛ �-7�6�fW\r\t�\b���W\"�\n�ə��L&���Ez�-����E��\t�%���/���O��Q����
i�����]�T�b�<_�dŦ�W۫���ܭn^[X�ϕ��{�"
I am expecting adecoded string. Any hint on this is much appreciated.
Thanks in Advance. :)

Related

How to decode Base64 String to png/jpg

def prop = testRunner.testCase.getTestStepByName("Kundendaten").getPropertyValue("phototandata")
//log.info( "Photo TAN property value= "+prop)
Base64 decoder = new Base64();
byte[] imgBytes = decoder.decode(prop);
FileOutputStream osf = new FileOutputStream(new File("B:\\Transfer\\haoot\\bild"));
osf.write(imgBytes);
osf.flush();
[No signature of method :java .util.Base64.decode() is applicale for
argument type error
Base64 decoder = new Base64();
byte[] imgBytes = decoder.getDecoder().decode(prop);

Lua decompress gzip from string

I have some trouble with decompress gzip from string in lua. (mb bad understanding)
Response of one web-services is base64-encoded gzip string, for sample I get some code on C#.
public static string Decompress(byte[] value, Encoding Encoding = null)
{
if (value == null) return null;
Encoding = Encoding ?? System.Text.Encoding.Unicode;
using (var inputStream = new MemoryStream(value))
using (var outputStream = new MemoryStream())
{
using (var zip = new GZipStream(inputStream, CompressionMode.Decompress))
{
byte[] bytes = new byte[4096];
int n;
while ((n = zip.Read(bytes, 0, bytes.Length)) != 0)
{
outputStream.Write(bytes, 0, n);
}
zip.Close();
}
return Encoding.GetString(outputStream.ToArray());
}
}
static void Main(string[] args)
{
const string encodedText = "H4sIAAAAAAAEAHMNCvIPUlRwzS0oqVQoLinKzEtXyC9SyCvNyYFxM/OAqKC0RKEgsSgxN7UktQgAwOaxgjUAAAA=";
byte[] decodedBytes = Convert.FromBase64String(encodedText);
var decodedString = Decompress(decodedBytes, Encoding.UTF8);
Console.WriteLine(decodedString);
}
I try to do this with lua (on nginx) and make from base64 string array of byte
local byte_table={};
base64.base64_decode(res_string):gsub(".", function(c){
table.insert(byte_table, string.byte(c))
})
but have some problem with zlib.
Please help me understanding how can I use IO stream in lua and decompress gzip.
I try to do this with lua (on nginx) and make from base64 string array of byte
No, you are making Lua table with bunch of numbers.
Decode base64 and feed to zlib the whole resulting string.
I'm use http://luaforge.net/projects/lzlib/ for gzip decompressing:
local result = zlib.decompress(str,31)

Writing to MemoryStream from BinaryReader

i am having an issue when trying to read saved List from binary file back to a List.
the file is encrypted, without encryption i had no problem.
writing method:
private void WriteEncodedFile(FileStream fileStream, MemoryStream memoryStream)
{
StreamReader sr = new StreamReader(memoryStream);
BinaryWriter bw = new BinaryWriter(fileStream);
memoryStream.Seek(0, SeekOrigin.Begin);
string data = sr.ReadToEnd();
var bytes = Encoding.UTF8.GetBytes(data);
for (int i = 0; i < bytes.Length; i++) bytes[i] ^= 0x5a;
bw.Write(Convert.ToBase64String(bytes));
bw.Close();
fileStream.Close();
}
Reading method:
private void ReadEncodedFile(FileStream fileStream, MemoryStream memoryStream)
{
BinaryReader br = new BinaryReader(fileStream);
StreamWriter sw = new StreamWriter(memoryStream);
fileStream.Seek(0, SeekOrigin.Begin);
memoryStream.Seek(0, SeekOrigin.Begin);
string base64 = br.ReadString();
byte[] bytes = Convert.FromBase64String(base64);
for (int i = 0; i < bytes.Length; i++) bytes[i] ^= 0x5a;
string decodedData = Encoding.UTF8.GetString(bytes);
sw.Write(decodedData);
}
when reading the content i can see it in the "decodedData".
however the StreamWriter seems not to write it into the MemoryStream.
any idea?
thanks.
I think you are simply not flushing/closing the stream before checking.
sw.Flush();
or
sw.Close();
if done
and
fileStream.Close(); for good practice too
Edit:
Considering the comment, you need to seek to start of memory stream again before deserialising
i.e. memoryStream.Seek(0, SeekOrigin.Begin); where-ever you do it

How to convert Base64 into BitmapImage and save it in Subforlder in Project

I need to retrieve image with webService which converted it into base64
and I need to convert this base64 into BitmapImage and save it into the folder which I added into project
I have these questions:
1) Do I have to convert Base64String into Stream and create a bitmapImage with it?
Can this BAse64 string be used as byte for creating bitmapImage without converting it to Buffer?
2) How to save the bitmapImage in the specific Folder after conversion from Base64 to buffer?
The problem:
no error and no image is saved!
I dont seems to be able to save it. Your help is greatly appreciated.
public async Task Base64StringToBitmapTask(string Base64source,string Filenm)
{
var ims = new InMemoryRandomAccessStream();
var bytes = Convert.FromBase64String(Base64source);
var dataWriter = new DataWriter(ims);
dataWriter.WriteBytes(bytes);
await dataWriter.StoreAsync();
ims.Seek(0);
var bm = new BitmapImage();
bm.SetSource(ims);
byte[] pixeBuffer = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wb = new WriteableBitmap(bm.PixelWidth,bm.PixelHeight);
await wb.SetSourceAsync(ims);
Stream s1 = wb.PixelBuffer.AsStream();
s1.CopyTo(ms);
pixeBuffer = ms.ToArray();
}
await InsertImageInFolder(pixeBuffer, Filenm);
}
private async Task InsertImageInFolder(byte[] buffer, string filename)
{
IBuffer Ibr = buffer.AsBuffer();
StorageFolder folder = ApplicationData.Current.LocalFolder;
//-1-- Get the folder added into the Project
StorageFolder subfolder = await StorageFolder.GetFolderFromPathAsync("ms-appx:///ProductImages");
//-2---- create a file in this folder
await subfolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
StorageFile sampleFile = await subfolder.GetFileAsync(filename);
await FileIO.WriteBufferAsync(sampleFile, Ibr);
}

Reading and Writing text file in Azure Storage

Following is the code to first save a line of text,into a text file,present in azure storage, and then read it and print .
string firstString = "this \t is \n a \t line \n are: ";
using (var memoryStream = new MemoryStream())
{
memoryStream.Write(System.Text.Encoding.UTF8.GetBytes(firstString), 0, System.Text.Encoding.UTF8.GetBytes(firstString).Length);
blockBlob.UploadFromStream(memoryStream);
}
string text;
using (var memoryStream = new MemoryStream())
{
blockBlob.DownloadToStream(memoryStream);
text = System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
Trace.WriteLine(text);
}
Problem is that nothing gets printed in the Trace.Writeline() Statement.
First i thought,that it might be a encoding issue,so i changed the format of my text file from ASCII to UTF8, but still nothing gets printed.
WHat am i missing here,any help is appreciated.
Replace the following line of code:
using (var memoryStream = new MemoryStream())
{
memoryStream.Write(System.Text.Encoding.UTF8.GetBytes(firstString), 0, System.Text.Encoding.UTF8.GetBytes(firstString).Length);
blockBlob.UploadFromStream(memoryStream);
}
with
using (var memoryStream = new MemoryStream())
{
memoryStream.Write(System.Text.Encoding.UTF8.GetBytes(firstString), 0, System.Text.Encoding.UTF8.GetBytes(firstString).Length);
memoryStream.Position = 0;
blob.UploadFromStream(memoryStream);
}
What's happening is that when you write the byte array to memoryStream, you're not resetting the position of stream to 0 thus a 0 byte blob is being uploaded.
When you use MemoryStream you first write to memory and after the write from memory to blob, it is better to write directly to blob, example:
using (var blobStream = blockBlob.OpenWrite())
{
var data = System.Text.Encoding.UTF8.GetBytes(firstString);
blobStream.Write(data, 0, data.Length);
}

Resources