Writing to MemoryStream from BinaryReader - streamreader

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

Related

FileInputStream can not read file always

I try to read a .raw audio file from the Android External Storage directory by using FileInputStream. Sometimes, I can read the file, sometimes not. What is the reason for this case?
Any help will be appreciated.
storageDir = Environment.getExternalStorageDirectory().getAbsolutePath();
enrollWavPath = storageDir + 1 + ".raw";
File file = new File(enrollRawPath);
byte[] byteData = null;
int size = (int) file.length();
byteData = new byte[(int)(size)];
FileInputStream iFileStream = new FileInputStream(file);
int bytesread = 0;
int ret = 0;
while (bytesread < size) {
ret = iFileStream.read( byteData,0, 2*count);
if (ret != -1) {
shortData = byte2short(byteData);
bytesread += ret;
}
else {
break;
}
}
iFileStream.close();

How to get an uncoded string from a base64 encoded gzipped text

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. :)

Reading the text file is not working in decryption, where i am going wrong here?

I have created an Encryption method to encrypt the data into test.txt Text file. The encryption is Working fine and its Reading the encryted text file into textBox1.
I m using 2 buttons and 2 textBox for doing this.
Now I want to Read the decryption text from test.txt in textBox2
but when i click on the button to read data from test.txt to textBox2.
I am getting an exception like (CryptographicException was unhandled) Bad Data.
Here is the code I used for Dycryption.
private void button2_Click(object sender, EventArgs e)
{
FileStream stream = new FileStream("C:\\test.txt",
FileMode.Open, FileAccess.Read);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateDecryptor(), CryptoStreamMode.Read);
StreamReader reader = new StreamReader(crStream);
//string data = reader.ReadToEnd();
textBox2.Text = reader.ReadLine();
//stream.Close();
}
Codes that i used for Encrytion is here:
private void button1_Click(object sender, EventArgs e)
{
FileStream stream = new FileStream("C:\\test.txt", FileMode.OpenOrCreate, FileAccess.Write);
DESCryptoServiceProvider cryptic = new DESCryptoServiceProvider();
cryptic.Key = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
cryptic.IV = ASCIIEncoding.ASCII.GetBytes("ABCDEFGH");
CryptoStream crStream = new CryptoStream(stream,
cryptic.CreateEncryptor(), CryptoStreamMode.Write);
byte[] data = ASCIIEncoding.ASCII.GetBytes(textBox2.Text);
crStream.Write(data, 0, data.Length);
crStream.Close();
stream.Close();
string text = System.IO.File.ReadAllText(#"C://test.txt");
textBox1.Text = text.ToString();
}
I don't know why you want to read it from test.txt file. when your displaying it in textbox. but check below code you can able to encrypt and decry-pt and meanwhile able to display and save in text boxes.
protected void Button1_Click(object sender, EventArgs e)
{
FileStream stream = new FileStream("C:\\test.txt", FileMode.OpenOrCreate, FileAccess.Write);
string datastring= Encrypt("ABCDEFGH", "ABCDEFGH");
byte[] data = ASCIIEncoding.ASCII.GetBytes(datastring);
stream.Write(data, 0, data.Length);
stream.Close();
string text = System.IO.File.ReadAllText(#"C:\\test.txt");
TextBox1.Text = text.ToString();
}
protected void Button2_Click(object sender, EventArgs e)
{
StreamReader reader =null;
try
{
FileStream stream = new FileStream("C:\\test.txt",
FileMode.Open, FileAccess.Read);
string fileContents;
using ( reader = new StreamReader(stream))
{
fileContents = reader.ReadToEnd();
}
string data = Decrypt(fileContents, "ABCDEFGH");
TextBox2.Text = data;
stream.WriteByte(Convert.ToByte(data));
stream.Close();
}
catch (Exception ex)
{
}
finally
{
reader.Close();
}
}
public static string Encrypt(string message, string password)
{
// Encode message and password
byte[] messageBytes = ASCIIEncoding.ASCII.GetBytes(message);
byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(password);
// Set encryption settings -- Use password for both key and init. vector
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateEncryptor(passwordBytes, passwordBytes);
CryptoStreamMode mode = CryptoStreamMode.Write;
// Set up streams and encrypt
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(messageBytes, 0, messageBytes.Length);
cryptoStream.FlushFinalBlock();
// Read the encrypted message from the memory stream
byte[] encryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
// Encode the encrypted message as base64 string
string encryptedMessage = Convert.ToBase64String(encryptedMessageBytes);
return encryptedMessage;
}
public static string Decrypt(string encryptedMessage, string password)
{
// Convert encrypted message and password to bytes
byte[] encryptedMessageBytes = Convert.FromBase64String(encryptedMessage);
byte[] passwordBytes = ASCIIEncoding.ASCII.GetBytes(password);
// Set encryption settings -- Use password for both key and init. vector
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateDecryptor(passwordBytes, passwordBytes);
CryptoStreamMode mode = CryptoStreamMode.Write;
// Set up streams and decrypt
MemoryStream memStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memStream, transform, mode);
cryptoStream.Write(encryptedMessageBytes, 0, encryptedMessageBytes.Length);
cryptoStream.FlushFinalBlock();
// Read decrypted message from memory stream
byte[] decryptedMessageBytes = new byte[memStream.Length];
memStream.Position = 0;
memStream.Read(decryptedMessageBytes, 0, decryptedMessageBytes.Length);
// Encode deencrypted binary data to base64 string
string message = ASCIIEncoding.ASCII.GetString(decryptedMessageBytes);
return message;
}

How to reduce memory while we Zip a big excel file in java

I am trying to zip a 30Mb excel file.
Wrapping th fileinputstream and fileoutputstream reduced some of the memory consumption.
Please suggest if you have a better option than this approach.
Do you think, flushing the ZipOutputStream after zos.write() inside while loop will be of any advantage?
Following is the code which i use.
public void zipBigFile()
throws IOException, ParseException {
String outFileName= "D:/Out/Big.zip";
File file = new File(outFileName);
FileOutputStream out = new FileOutputStream(file);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(out));
byte[] buffer = new byte[1024 * 8];
String inFileName = "D:/In/Big_File.xlsx";
FileInputStream fis = new FileInputStream(inFileName);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipEntry zipEntry = new ZipEntry("Big_File_Zipped.xlsx");
zos.putNextEntry(zipEntry);
int length;
while ((length = bis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
fis.close();
fis = null;
buffer = null;
zos.flush();
zos.close();
out.close();
out = null;
zos = null;
}

how to use Management API in Windows Form / C# - but The remote server returned an error: (400) Bad Request

I have a problem in API Management, I want to create images in item 1 item, but I still can not do it forever. I use c # language, I feel depressed
i want to create a resource in catchoom.
can you help me
byte[] buffer = null;
byte[] data = null;
byte[] data1 = null;
HttpWebRequest request = null;
int bytesRead = 0;
long length = 0;
string boundary = DateTime.Now.Ticks.ToString("x");
// string boundary = "AaB03x";
StringBuilder sb = null;
// Create the HttpWebRequest object
request = (HttpWebRequest)HttpWebRequest.Create("https://crs.catchoom.com/api/v0/image/?api_key=5aba12ba6974c04ebc95da45ba1597d27d75238f");
// Specify the ContentType
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";
// Specify the Method
request.Method = "POST";
request.KeepAlive = false;
// Create the StringBuilder object
sb = new StringBuilder();
// Constrcut the POST header message
sb.AppendLine("");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: form-data; name=\"anh\"");
sb.AppendLine("");
sb.AppendLine("/api/v0/item/aee726ff67274fcb80f4c24f27861c1e/");
sb.AppendLine("--" + boundary);
sb.AppendLine("Content-Disposition: file; name=\"anh\"; filename=\"anh\"");
sb.AppendLine("Content-Type: image/jpg");
sb.AppendLine("");
StringBuilder sb1 = new StringBuilder();
sb1.AppendLine("");
sb1.AppendLine("--" + boundary + "--");
// Convert the StringBuilder into a string
data = Encoding.UTF8.GetBytes(sb.ToString());
data1 = Encoding.UTF8.GetBytes(sb1.ToString());
//
using (FileStream fs = new FileStream(#"D:\17. NHATLINH\ToolKit_Catchoom\ToolKit_Catchoom\bin\Debug\aa.jpg", FileMode.Open, FileAccess.Read))
{
length = data.Length + fs.Length + data1.Length;
// đưa thông tin chiều dài của gói gửi đi vào
request.ContentLength = length;
//
using (Stream stream = request.GetRequestStream())
{
// ghi header vào gói gửi đi
stream.Write(data, 0, data.Length);
//
buffer = new Byte[checked((uint)Math.Min(4096, (int)fs.Length))];
// buffer = new Byte[fs.Length];
// Write the file contents
while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0)
{
stream.Write(buffer, 0, bytesRead);
}
stream.Write(data1, 0, data1.Length);
//
try
{
Console.WriteLine(request.ContentType);
Console.WriteLine(sb.ToString() + sb1.ToString());
WebResponse responce = request.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
MessageBox.Show(sr.ReadToEnd());
}
catch (Exception ec)
{
MessageBox.Show(ec.Message);
}
}
}
Building a multipart-encoded request is an error-prone task ( it is normal if you feel frustrated trying ), I recommend you to use a library to handle this kind of things, no point in reinventing the wheel :)
If you are using the Microsoft .NET Framework >= 4.5, you may use the HttpClient class as this answer explains.
Hope this help you ;)

Resources