470,561 Members | 2,307 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,561 developers. It's quick & easy.

Convert binary file->utf8->binary file


Hi,
Does anyone know how I am able to write a utf-8 encoded binary string into
binary file?
Currently I am given a UTF-8 string which was read from a gif image.

Here are my functions...

public Byte[] GetDocument(string DocumentName)
{
string strdocPath;
strdocPath = DocumentName;
FileStream objfilestream = new
FileStream(strdocPath,FileMode.Open,FileAccess.Rea d);
int len = (int)objfilestream.Length;
Byte[] documentcontents = new Byte[len];
objfilestream.Read(documentcontents,0,len);
objfilestream.Close();
return documentcontents;
}
public static string FromUTF8ByteArray(Byte[] characters)
{
System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
string constructedString = encoding.GetString(characters);
return (constructedString);
}

public class RawEncoding
{
public static Byte[] GetBytes(string text)
{
Byte[] result = new Byte[text.Length];
for(int i = 0; i < text.Length; ++i)
{
result[i] = (Byte)text[i];
}
return result;
}
}

Byte[] utf8Bytes =
RawEncoding.GetBytes(FromUTF8ByteArray(GetDocument (FILE_NAME)));
Byte[] finalBytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode,
utf8Bytes);
string fileName = "test.gif";
FileStream fst = new FileStream(file_name, FileMode.Create);
fst.Write(finalBytes, 0, finalBytes.Length);
fst.Flush();
fst.Close();

Thanks

Nov 17 '05 #1
2 10448
Hi Joey,

I'm not sure you can safely convert a binary file to UTF8 without loss of data, but the procedure to convert the data to a file is to retrieve the bytes and feed them to a FileStream

string utf8String = // some value

byte[] data = Encoding.UTF8.GetBytes(s);
FileStream fs = File.Create("NewFile.gif");
fs.Write(data, 0, data.Length);
fs.Close();
--
Happy coding!
Morten Wennevik [C# MVP]
Nov 17 '05 #2
Joey Lee <jo*********@hotmail.com> wrote:
Does anyone know how I am able to write a utf-8 encoded binary string into
binary file?
Currently I am given a UTF-8 string which was read from a gif image.


That's a really, really bad idea. You can't just read arbitrary data
and assume it's a valid UTF-8 encoded string.

If you wish to turn arbitrary data into text, I suggest you use Base64
(see Convert.ToBase64String and Convert.FromBase64String).

--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
Nov 17 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Spamtrap | last post: by
2 posts views Thread by geekboyed | last post: by
1 post views Thread by Hooyoo | last post: by
4 posts views Thread by EmeraldShield | last post: by
1 post views Thread by John Nagle | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.