How to read kmz stream to parse kml on Windows Phone 7 - c#

I want to convert a kmz stream to a kml stream to parse it.
I tried this to do that with SharpZipLib because I read that kmz is just an zipfile of the kml.
My code :
ZipInputStream zipInputStream = new ZipInputStream(myKmzStream);
ZipEntry zipEntry = zipInputStream.GetNextEntry();
// here, zipEntry as a name "doc.kml"
//but zipEntry.ExtraData is null...
byte[] kmlContent = zipEntry.ExtraData; // null
Is there any reason I get this result ?
Thanx for help :)

My opinion is that ExtraData is not set (that why the null value). You need to extract the data from the ZIP (KMZ) file out to a stream to parse it further.
Take a look at this sample:
https://github.com/icsharpcode/SharpZipLib/wiki/Zip-Samples#-unpack-a-zip-with-full-control-over-the-operation
Hope it helps!
Cheers,

Related

How do I read the correct Stream/byte[] from HttpPostedFile InputStream property?

I get a HttpPostedFile that is being uploaded (supposedly a pdf), and I have to use it's stream to initialize it in PdfSharp.
The problem is that, altough HttpPostedFile SaveAs() method saves a valid pdf, saving it's InputStream doesn't create a valid pdf, so when I use the InputStream on PdfSharp to read the pdf it throws an exception with "Invalid Pdf", and saving the InputStream byte[]
which I tried to get like this:
public byte[] GetBytesFromStream(System.IO.Stream uploadedFile)
{
int length = Convert.ToInt32(uploadedFile.Length); //Length: 103050706
string str = "";
byte[] input = new byte[length];
// Initialize the stream.
System.IO.Stream MyStream = uploadedFile;
// Read the file into the byte array.
MyStream.Read(input, 0, length);
return input;
}
Calling the method like this:
byte[] fileBytes = GetBytesFromStream(uploadedFile.InputStream);
But creating a file from those bytes creates an invalid pdf too...
I created the file from bytes like this...
System.IO.File.WriteAllBytes("Foo.pdf", fileBytes);
I have 2 questions about this then:
1st - Why is the stream I receive from the InputStream invalid, and the SaveAs Works.
2nd - How could I get the correct stream from the inputStream or the HttpPostedFile, without saving the file to disk and then reading it.
Noticed that this question wasn't answered (since Evk's comment was the solution) and I couldn't accept any answer.
So I'm making this one just to not leave this question unanswered.
tl;dr;
The solution as per Evk's comment was the position of the stream, it was being read beforehand and setting the position to 0 before trying to create the pdf was enough to fix the problem.

Replace Text in a TextFile c#

What is the best way to replace text in a text file?
I do not want to give the file a new name
I do not want the text to become one long string which is what happens when I use File.ReadAllText because this is stored as a string and I loose carriage returns etc...
Also, I guess I will run into issues using a StreamReader/StreamWriter because you cannot read and write to the same file?
Thanks
You can do it with a stream opened for both reading and writing:
FileStream fileStream = new FileStream(#"c:\myFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
var streamWriter = new StreamWriter(fileStream);
var streamReader = new StreamReader(fileStream);
...
fileStream .Close();
But the most easy way is still to read all file, edit the text and write it back to the file:
var text = File.ReadAllText(#"c:\myFile.txt");
...
File.WriteAllText(#"c:\myFile.tx", text);
Depending on your file format, you could also read your files line by line (using File.ReadLines) and perform the text replacements for each line.
You can also refer to this answer for a variant based on streams, which is the preferred way if your file is large.
How to read a large (1 GB) txt file in .NET?

Decompressing a Zip file from a string

I'm fetching an object from couchbase where one of the fields has a file. The file is zipped and then encoded in base64.
How would I be able to take this string and decompress it back to the original file?
Then, if I'm using ASP.MVC 4 - How would I send it back to the browser as a downloadable file?
The original file is being created on a Linux system and decoded on a Windows system (C#).
You should use Convert.FromBase64String to get the bytes, then decompress, and then use Controller.File to have the client download the file. To decompress, you need to open the zip file using some sort of ZIP library. .NET 4.5's built-in ZipArchive class should work. Or you could use another library, both SharpZipLib and DotNetZip support reading from streams.
public ActionResult MyAction()
{
string base64String = // get from Linux system
byte[] zipBytes = Convert.FromBase64String(base64String);
using (var zipStream = new MemoryStream(zipBytes))
using (var zipArchive = new ZipArchive(zipStream))
{
var entry = zipArchive.Entries.Single();
string mimeType = MimeMapping.GetMimeMapping(entry.Name);
using (var decompressedStream = entry.Open())
return File(decompressedStream, mimeType);
}
}
You'll also need the MIME type of the file, you can use MimeMapping.GetMimeMapping to help you get that for most common types.
I've used SharpZipLib successfully for this type of task in the past.
For an example that's very close to what you need to do have a look here.
Basically, the steps should be something like this:
you get the compressed input as a string from the database
create a MemoryStream and write the string to it
seek back to the beginning of the memory stream
use the MemoryStream as an input to the SharpZipLib ZipFile class
follow the example provided above to unpack the contents of the ZipFile
Update
If the string contains only the zipped contents of the file (not a full Zip archive) then you can simply use the GZipStream class in .NET to unzip the contents. You can find a sample here. But the initial steps are the same as above (get string from db, write to memory stream, feed memory stream as input to the GZipStream to decompress).

How to read all text from a byte[] file?

I have a text file in the form of a byte[].
I cannot save the file anywhere.
I would like to read all lines/text from this 'file'.
Can anyone point me in the right direction on how I can read all the text from a byte[] in C#?
Thanks!
I would create a MemoryStream and instantiate a StreamReader with that, i.e:
var stream = new StreamReader(new MemoryStream(byteArray));
Then get the text a line at a time with:
stream.readLine();
Or the full file using:
stream.readToEnd();
Another possible solution using Encoding:
Encoding.Default.GetString(byteArray);
It can optionally be split to get the lines:
Encoding.Default.GetString(byteArray).Split('\n');
You can also select a particular encoding like UTF-8 instead of using Default.

Reliable way to convert a file to a byte[]

I found the following code on the web:
private byte [] StreamFile(string filename)
{
FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read);
// Create a byte array of file stream length
byte[] ImageData = new byte[fs.Length];
//Read block of bytes from stream into the byte array
fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));
//Close the File Stream
fs.Close();
return ImageData; //return the byte data
}
Is it reliable enough to use to convert a file to byte[] in c#, or is there a better way to do this?
byte[] bytes = System.IO.File.ReadAllBytes(filename);
That should do the trick. ReadAllBytes opens the file, reads its contents into a new byte array, then closes it. Here's the MSDN page for that method.
byte[] bytes = File.ReadAllBytes(filename)
or ...
var bytes = File.ReadAllBytes(filename)
Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:
System.IO.File.ReadAllBytes(filename);
File.Exists(filename)
Path.Combine(folderName, resOfThePath);
Path.GetFullPath(path); // converts a relative path to absolute one
Path.GetExtension(path);
All these answers with .ReadAllBytes(). Another, similar (I won't say duplicate, since they were trying to refactor their code) question was asked on SO here: Best way to read a large file into a byte array in C#?
A comment was made on one of the posts regarding .ReadAllBytes():
File.ReadAllBytes throws OutOfMemoryException with big files (tested with 630 MB file
and it failed) – juanjo.arana Mar 13 '13 at 1:31
A better approach, to me, would be something like this, with BinaryReader:
public static byte[] FileToByteArray(string fileName)
{
byte[] fileData = null;
using (FileStream fs = File.OpenRead(fileName))
{
var binaryReader = new BinaryReader(fs);
fileData = binaryReader.ReadBytes((int)fs.Length);
}
return fileData;
}
But that's just me...
Of course, this all assumes you have the memory to handle the byte[] once it is read in, and I didn't put in the File.Exists check to ensure the file is there before proceeding, as you'd do that before calling this code.
looks good enough as a generic version. You can modify it to meet your needs, if they're specific enough.
also test for exceptions and error conditions, such as file doesn't exist or can't be read, etc.
you can also do the following to save some space:
byte[] bytes = System.IO.File.ReadAllBytes(filename);
Others have noted that you can use the built-in File.ReadAllBytes. The built-in method is fine, but it's worth noting that the code you post above is fragile for two reasons:
Stream is IDisposable - you should place the FileStream fs = new FileStream(filename, FileMode.Open,FileAccess.Read) initialization in a using clause to ensure the file is closed. Failure to do this may mean that the stream remains open if a failure occurs, which will mean the file remains locked - and that can cause other problems later on.
fs.Read may read fewer bytes than you request. In general, the .Read method of a Stream instance will read at least one byte, but not necessarily all bytes you ask for. You'll need to write a loop that retries reading until all bytes are read. This page explains this in more detail.
string filePath= #"D:\MiUnidad\testFile.pdf";
byte[] bytes = await System.IO.File.ReadAllBytesAsync(filePath);

Categories