C#: Barcode to byte array to valid zip file - c#

I'm scaning a Pdf417 barcode which returns me a byte[] array. The DataString itself is a cryptic value like face to keyboard multiple times and fast. So I'm guessing it could be a zip file which is stored in the barcode. In the zip file there should be a xml file.
I had different attempts so far to convert my byte[] array to a valid zip file. In the end I was never able to open said zip file.
The barcodes are created by certified software solutions, so the barcode is not the problem for sure.
I can't be the only one who has had this problem, right?
Output when reading a barcode with dummy data in it:
"\0\0\0\vz\0\u0002B\u0001\u0002PK\u0003\u0004\n\0\0\0\b\0 E\u0081Q|\u0015\u00163Î\u0001\0\0\u0004\u0004\0\0\u0004\0\0\0txab}SMo£0\u0010½ï¯°|\a\u001bª¤Ý\u0015Påc\u0093Fê&\b²9ôÆÂ$ \r¦²M\u0093üûNø\b$Që\u008bí7ï½\u0019{lçù\u0098ïÉ\aH\u0095\u0015Â¥\u0096É)\u0001\u0011\u0017I&v.ý»\u009e\u0019OôÙsÖ\u0004iB¹4Õúý\u0017c\u0087ÃÁT\u0087L©\u0004b3N\u0099\u008aSÈ#¦\u0012fs>ä6·X\u0018í#y\u009aB\u008cS¤Ñ}}\u001c\u008d)\t\u0017S\u0097ÎV+\\u009dÔ¦^z?\b\u000egRäï\u00918\u0091\u0097À\b&Æ2ÊÁ¥/\u0091Pä\u000fd ÉhNÉÛÂwé\u0013ç\u009c²Fäcé\u0085XLÉk¤´¨4\u0015\u009d\u0092Y&[äìÒ\u0017×ÚJ\u001fn\u008cQh,¥÷8\u0018\u009a\u0016\u000eÓÆa>ütØ%Tgbmªf\u001fö\0\u0094\u0015I\aTàV\u0016¹gãe\u0018|`pËa\u0015pÍ)\u0085Îö5ɲ\u008d\a$ÕHgÍn½\u009d\u0005ö'\ao\u0080'á&ç\u000ek\u0080\u008e1\u0093Ø>\u0018\u0083\u0080m¦\u0015ëEV:\u0005Ù\u0006njYÃQ{ãB\u0094ÊaÕú:\u001c\u0096¹g]r\u009ew½"¿ðuæ²Pª©ox\u0011÷Ñ\u008e;ÞÌ\u008dWß7&\u0085Ð2ûW\u009e\u001fÍM\r\u0001ìJ|Oxa\u008dS\v\ÓüRÆi¤ ª·â]\u0090^Íßçs\u0096 Û\u009b~lm:¬ãM!)ã³v¤Ã\u0002Óô²Þ\u0087:Ù$\u008dä\u000eTPî\u0081ÝÃ7\aú½Ý\u0002\u001a}\QÙ\u001d·nï×Ý\u000fð\u0093Êÿí×aø\u0082±ÓÞ'PK\u0001\u0002\u0014\0\n\0\0\0\b\0 E\u0081Q|\u0015\u00163Î\u0001\0\0\u0004\u0004\0\0\u0004\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0txabPK\u0005\u0006\0\0\0\0\u0001\0\u0001\02\0\0\0ð\u0001\0\0\0\0"
Dont pay too much attention to this function, at this stage I'm probably trying too much to get to a solution. This is just one of many test voids of mine.
public void Test(byte[] bytes)
{
byte[] zipBytes;
using (var memoryStream = new MemoryStream())
{
using (var zipArchive = new ZipArchive(memoryStream, ZipArchiveMode.Create, leaveOpen: true))
{
var zipEntry = zipArchive.CreateEntry("test");
using (Stream entryStream = zipEntry.Open())
{
entryStream.Write(bytes, 0, bytes.Length);
}
}
zipBytes = memoryStream.ToArray();
}
using (var fileStream = new FileStream(#"C:\BarcodeReaderTesting\test.zip", FileMode.OpenOrCreate))
{
fileStream.Write(zipBytes, 0, zipBytes.Length);
}
}
Any tips on this topic?

Related

Saving MemoryStream to File produces 0 bytes

I'm using this code to write an MP3 MemoryStream to file:
using (var nSpeakStreamAsMp3 = new MemoryStream())
using (var nWavFileReader = new WaveFileReader(nSpeakStream))
using (var nMp3Writer = new LameMP3FileWriter(nSpeakStreamAsMp3, nWavFileReader.WaveFormat, LAMEPreset.STANDARD_FAST))
{
nWavFileReader.CopyTo(nMp3Writer);
string sPath = "C:\\inetpub\\wwwroot\\server\\bin\\mymp3.mp3";
using (FileStream nFile = new FileStream(sPath, FileMode.Create, System.IO.FileAccess.Write))
{
nSpeakStreamAsMp3.CopyTo(nFile);
}
sRet = (String.Concat("data:audio/mpeg;base64,", Convert.ToBase64String(nSpeakStreamAsMp3.ToArray())));
}
return sRet;
For some reason which I don't see, this produces a file of 0 bytes.
However, the MP3 stream is valid and does work. I'm passing it as a Base64String to a website, and I do hear it.
Where might be the error here?
nSpeakStreamAsMp3 is currently positioned at the end of the stream; you need to think like a VCR: be kind, rewind (nSpeakStreamAsMp3.Position = 0;) before you copy the value out again
make sure you flush nMp3Writer; if possible, close nMp3Writer completely

create zip from byte[] and return to browser

I want to create a zip-file and return it to the browser so that it downloads the zip to the downloads-folder.
var images = imageRepository.GetAll(allCountryId);
using (FileStream f2 = new FileStream("SudaAmerica", FileMode.Create))
using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
{
foreach (var image in images)
{
gz.Write(image.ImageData, 0, image.ImageData.Length);
}
return base.File(gz, "application/zip", "SudaAmerica");
}
i have tried the above but then i get an error saying the stream is disposed.
Is this possible or should i use another library then gzipstream?
The problem here is exactly what it says: you are handing it something based on gz, but gz gets disposed the moment you leave the using.
One option would be to wait until outside the using block, then tell it to use the filename of the thing you just wrote ("SudaAmerica"). However, IMO you shouldn't actually be writing a file here at all. If you use a MemoryStream instead, you can use .ToArray() to get a byte[] of the contents, which you can use in the File method. This requires no IO access, which is a win in about 20 different ways. Well, maybe 3 ways. But...
var images = imageRepository.GetAll(allCountryId);
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress, false))
{
foreach (var image in images)
{
gz.Write(image.ImageData, 0, image.ImageData.Length);
}
}
return base.File(ms.ToArray(), "application/zip", "SudaAmerica");
}
Note that a gzip stream is not the same as a .zip archive, so I very much doubt this will have the result you want. Zip archive creation is available elsewhere in the .NET framework, but it is not via GZipStream.
You probably want ZipArchive

Nancy httpfile issue

i have problems during parsing request files.
my file size is 1338521 bytes, but Nancy says, that file size is some times 1751049 or 3200349.
on my windows pc it works fine, on linux server this problem appears, so i can't save file.
string result = Convert.ToBase64String(Core.ReadBytesFromStream(file.Value));
using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(result)))
{
using (Bitmap bm2 = new Bitmap(ms))
{
bm2.Save(path);
}
}
any ideas?
You don't need to convert the file like that.
var filename = Path.Combine(storagePath, Request.Files[0].Name);
using (var fileStream = new FileStream(filename, FileMode.Create))
{
Request.Files[0].Value.CopyTo(fileStream);
}
Validate the file when it comes in to ensure the extension is accepted, create a save path, and copy the stream to a new file on the filesystem.
That's it.

Read a PDF into a string or byte[] and write that string/byte[] back to disk

I am having a problem in my app where it reads a PDF from disk, and then has to write it back to a different location later.
The emitted file is not a valid PDF anymore.
In very simplified form, I have tried reading/writing it using
var bytes = File.ReadAllBytes(#"c:\myfile.pdf");
File.WriteAllBytes(#"c:\output.pdf", bytes);
and
var input = new StreamReader(#"c:\myfile.pdf").ReadToEnd();
File.WriteAllText("c:\output.pdf", input);
... and about 100 permutations of the above with various encodings being specified. None of the output files were valid PDFs.
Can someone please lend a hand? Many thanks!!
In C#/.Net 4.0:
using (var i = new FileStream(#"input.pdf", FileMode.Open, FileAccess.Read))
using (var o = File.Create(#"output.pdf"))
i.CopyTo(o);
If you insist on having the byte[] first:
using (var i = new FileStream(#"input.pdf", FileMode.Open, FileAccess.Read))
using (var ms = new MemoryStream())
{
i.CopyTo(ms);
byte[] rawdata = ms.GetBuffer();
using (var o = File.Create(#"output.pdf"))
ms.CopyTo(o);
}
The memory stream may need to be ms.Seek(0, SeekOrigin.Origin) or something like that before the second CopyTo. look it up, or try it out
You're using File.WriteAllText to write your file out.
Try File.WriteAllBytes.

sharpziplib compressed files to be uncompressed externally

I have a scenario where by I want to zip an email attachment using SharpZipLib. Then the end user will open the attachment and will unzip the attached file.
Will the file originally zipped file using SharpZipLib be easily unzipped by other programs for my end user?
It depends on how you use SharpZipLib. There is more than one way to compress the data with this library.
Here is example of method that will create a zip file that you will be able to open in pretty much any zip aware application:
private static byte[] CreateZip(byte[] fileBytes, string fileName)
{
using (var memoryStream = new MemoryStream())
using (var zipStream = new ZipOutputStream(memoryStream))
{
var crc = new Crc32();
crc.Reset();
crc.Update(fileBytes);
var zipEntry =
new ZipEntry(fileName)
{
Crc = crc.Value,
DateTime = DateTime.Now,
Size = fileBytes.Length
};
zipStream.PutNextEntry(zipEntry);
zipStream.Write(fileBytes, 0, fileBytes.Length);
zipStream.Finish();
zipStream.Close();
return memoryStream.ToArray();
}
}
Usage:
var fileBytes = File.ReadAllBytes(#"C:/1.xml");
var zipBytes = CreateZip(fileBytes, "MyFile.xml");
File.WriteAllBytes(#"C:/2.zip", zipBytes);
This CreateZip method is optimized for the cases when you already have bytes in memory and you just want to compress them and send without even saving to disk.

Categories

Resources