Question

I have a file that exists within a text and a binary image, I need to read from 0 to 30 position the text in question, and the position on 31 would be the image in binary format. What are the steps that I have to follow to proceed with that problem?

Currently, I am trying to read it using FileStream, and then I move the FileStream var to one BinaryReader as shown below:

FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read)
BinaryReader br = new BinaryReader(fs)

From there forward, I'm lost.


UPDATE

Alright, so I Can read my file now. Until the position 30 is my 30 string, from position 30 is the bit string Which is Actually an image. I wonder how do I read the bytes from position 30 and then save the images! Does anyone have any ideas? Follow an example from my file to you have some ideia:

£ˆ‰¢@‰¢@¢–”…@•…¦@„£@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@.-///%<<??@[K}@k{M÷]kðñôôô}ù~øòLKóôòÿg

Note that even the @ @ @ is my string and from that the picture would be one byte.

Was it helpful?

Solution

Expanding on Roger's answer a bit, with some code.

A string is always encoded in some format, and to read it you need to know that encoding (especially when using binary reader). In many cases, it's plain ASCII and you can use Encoding.ASCII.GetString to parse it if you get unexpected results (weird characters etc.) then try another encoding.

To parse the image you need to use an image parser. .NET has several as part of their GUI namespaces. In the sample below I'm using the one from System.Drawing (windows forms) but similar ones exists in WPF and there are many third party libraries out there.

using (var reader = new BinaryReader(File.Open(someFile, FileMode.Open))
{
    // assuming your string is in plain ASCII encoding:
    var myString = System.Text.Encoding.ASCII.GetString(reader.ReadBytes(30));
    // The rest of the bytes is image data, use an image library to process it
    var myImage = System.Drawing.Image.FromStream(reader.BaseStream);
}

Now MSDN has a caution about using the BaseStream in conjunction with BinaryReader but I believe in the above case you should be safe since you're not using the stream after the image. But keep an eye out for problems. If it fails, you can always read the bytes into a new byte[] and create a new MemoryStream from those bytes.

EDIT:

You indicated in your comment your string is EBCDIC which unfortunately means you cannot use any of the built in Encodings to decode it. A quick google search revealed a post by Jon Skeet on a EBCDIC .NET Encoding class that may get you started. It will essentially give you ebcdicEncoding.GetString(...);

OTHER TIPS

You can use FileStream to open and read from the file. If you read the first 30 bytes into a buffer you can then convert that to a string using "string Encoding.ASCII.GetString(byte[] buffer, int offset, int length)".

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top