473,770 Members | 2,120 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can C# string contain binary data?

Why is binary array written to a file different
than when converting the binary array to string
and then writing it to file! For example:
// --- Allocate byte array
byte [] arrByte = new byte[255];
for( int i=1; i< arrByte.Length; i++ )
arrByte[i] = (byte)i;

// --- Create two file handlers
string file = "BinaryFile ";
FileStream fs1 = new FileStream( file + "1", FileMode.Create );
FileStream fs2 = new FileStream( file + "2", FileMode.Create );
BinaryWriter w1 = new BinaryWriter( fs1 );
BinaryWriter w2 = new BinaryWriter( fs2 );

// --- Econde binary to string
System.Text.Enc oding enc = System.Text.Enc oding.GetEncodi ng("iso-8859-1");
string str = enc.GetString( this.arrByte );

// --- Write data to file
w1.Write( str ); // why is w1 file != w2 file?
w2.Write( arrByte );

w2.Close();
w2.Close();
Needless to say, I've attempted using several different encodings when
converting binary array to string.

The above example demonstrates the issue. I can't use encoding/decoding or
[Serializable], because I have binary data that needs to be returned as a
string to classic asp application, which uses .NET component responsible for
data retrival.

If it helps, here is what I am intending to do...

Classic ASP calls a COM object (written in C#) which does some socket
communication. In my case, contents of a PDF files are obtained. Because
classic ASP does not recognize Byte datatype (array obtained from socket), I
need to convert it to string where the ASP page will use
Response.Binary Write( myBinString ).

In my test files I found that I am unable to convert a binary array to
string successfully. In the past, we used vb6 that used String to store the
result from the Socket Communication. Thus, I believe I should be able to
store binary data in string within the c# language! Which the string will
ultimately be returned to the classic ASP.

The above sample code demonstrates the content of a string written to file
is not same as a binary array! Why is this so, and what am I missing?

Thanks in advance
Jun 6 '06 #1
2 13128
Edvin <Ed***@discussi ons.microsoft.c om> wrote:
Why is binary array written to a file different
than when converting the binary array to string
and then writing it to file! For example:
// --- Allocate byte array
byte [] arrByte = new byte[255];
for( int i=1; i< arrByte.Length; i++ )
arrByte[i] = (byte)i;

// --- Create two file handlers
string file = "BinaryFile ";
FileStream fs1 = new FileStream( file + "1", FileMode.Create );
FileStream fs2 = new FileStream( file + "2", FileMode.Create );
BinaryWriter w1 = new BinaryWriter( fs1 );
BinaryWriter w2 = new BinaryWriter( fs2 );

// --- Econde binary to string
System.Text.Enc oding enc = System.Text.Enc oding.GetEncodi ng("iso-8859-1");
string str = enc.GetString( this.arrByte );

// --- Write data to file
w1.Write( str ); // why is w1 file != w2 file?
w2.Write( arrByte );

w2.Close();
w2.Close();


Writing a string to a binary writer uses the encoding associated with
the binary writer. First it writes the byte length as a 7-bit encoded
number (so that short strings don't take up too many bytes), and then
gets the bytes for the string according to the encoding associated with
the BinaryWriter. The encoding is specified in the constructor of
BinaryWriter, but it defaults to UTF8 if you don't specify it.

The differences in your case with w2:

1) A different encoding is used, iso-8859-1.
2) The byte array is written out, but the length of the byte array
isn't.

-- Barry

--
http://barrkel.blogspot.com/
Jun 6 '06 #2
On Tue, 6 Jun 2006 11:58:01 -0700, Edvin wrote:
Why is binary array written to a file different
than when converting the binary array to string
and then writing it to file! For example:


That's because most caracter encodings do not map every possible byte
values to a displayable caracter. Have a look at the ASCII encoding table
for example and you'll see that many byte values do not map to any caracter
at all or map to non-displayable caracters such as \0, TAB or BEEP. So you
need to use a caracter encoding that can map every possible byte value to a
displayable caracter. Fortuanately, there is one and it's called Base 64.
Have a look at Convert.ToBase6 4String().
Jun 6 '06 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
4476
by: Achim Domma | last post by:
Hi, I want to pass raw binary data from a file to a COM object. I read the data from file like this: data = file('path_to_file','rb').read() If passed to a COM object, data is converted to unicode in the way one would expect for strings. I.e. a lot of zeros are filled in. I want each two characters from data to be interpreted as one unicode character. I read the
1
8770
by: Niko Korhonen | last post by:
I'm currently in the process of programming a multimedia tagging library in standard C++. However, I've stumbled across one or two unclear issues while working with the library. First of all, is it safe to store binary data in std::string? This question rose from my implementation with APEv2 tags. An APEv2 tag's field value can contain either UTF encoded text or binary data. I've decided to use std::string to represent the field value....
10
14606
by: Angus Comber | last post by:
Hello My code below opens a Word document in binary mode and places the data into a buffer. I then want to search this buffer for a string. I tried using strstr but think it stops looking when it reaches first null character or some control character in data. What C function should I use to be able to search in a BYTE data buffer? Code:
9
6279
by: Durgesh Sharma | last post by:
Hi All, Pleas help me .I am a starter as far as C Language is concerned . How can i Right Trim all the white spaces of a very long (2000 chars) Charecter string ( from the Right Side ) ? or how can i make a fast Right Trim Function in c,using Binary search kind of fast algorithm ? Offcourse...I can use the classical approach too. like : Start from the right most charecter of the string to the left of the
10
2386
by: jt | last post by:
I'm needing to take a binary string start at a certain position and return a pointer from that postion to the end of the binary stirng. something like this: char bstr; char *pos; pos=mid(bstr,35); / *return a pointer of the rest of the binary string starting at element 35 */
26
2584
by: alberto | last post by:
Hi. Im newbie in C language. I have a binary file with many character arrays of 50 character defined as char array But in some cases, many of these 50 characters are not being used. I would like to know how could I know how many characters are really being used in each array ? Thanks
13
6127
by: Pep | last post by:
I have to interface to an older library that uses strings and there is no alternative. I need to pass a string that is padded with null bytes. So how can I append these null bytes to the std::string? Yes I know it would be better to use something like a vector but I do not have that option. Yes I know that I will not be able to use std::string.c_str() but will instead have to use std:;string.getData().
11
3665
by: coomberjones | last post by:
I have a few std::strings that I am using to store raw binary data, each of which may very well include null bytes at any point or points. I want to slap them together into a single string, so I tried a std::ostringstream: std::ostringstream oss; oss << x << y << z; std::string result ( oss.str() ); The result shows that feeding the ostringstream with a string just
6
5284
by: Bob Altman | last post by:
Hi all, I'm looking for the fastest way to convert an array of bytes to String. I also need to convert a String back to its original Byte() representation. Convert.ToBase64String and Convert.FromBase64String seem like the closest thing I can find to what I'm looking for baked into the base class library. Can anyone suggest a better way to do this? TIA - Bob
0
9618
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10260
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10038
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8933
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7456
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5354
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5482
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4007
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2850
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.