About FileStream and StreamWriter!?

V

Viorel

About FileStream and StreamWriter!?



I have a string1 which contains(of course in unicode) a html code with
Unicode charset specified in it.

1)

byte[]content= System.Text.UnicodeEncoding.Unicode.GetBytes(string1);

System.IO.FileStream wr=new System.IO.FileStream("C:\\myhtml.html"
,System.IO.FileMode.CreateNew);

wr.Write(content,0,content.Length);

wr.Close();



When I opened the file some characters are unreadable, so something is wrong
in my code above, but then I have done:

2)

byte[]content= System.Text.UnicodeEncoding.Unicode.GetBytes(string1);

//System.IO.FileStream wr=new //System.IO.FileStream("C:\\myhtml.html"
,System.IO.FileMode.CreateNew);

//wr.Write(content,0,content.Length);

//wr.Close();



System.IO.StreamWriter tr=new System.IO.StreamWriter("C:\\myhtml.html"
,,false,System.Text.Encoding.Unicode);

string teststr=System.Text.Encoding.Unicode.GetString(content);

tr.Write(teststr);//(I did not simply used string1 in it because of reason
of testing)



And file was in good form, why first time wasn't good as second?



Tanks to all!
 
J

Jon Skeet

Viorel said:
About FileStream and StreamWriter!?

I have a string1 which contains(of course in unicode) a html code with
Unicode charset specified in it.

1)

byte[]content= System.Text.UnicodeEncoding.Unicode.GetBytes(string1);

Note that UnicodeEncoding.Unicode is more canonically known as just
Encoding.Unicode.
System.IO.FileStream wr=new System.IO.FileStream("C:\\myhtml.html"
,System.IO.FileMode.CreateNew);

wr.Write(content,0,content.Length);

wr.Close();

When I opened the file some characters are unreadable, so something is wrong
in my code above

No, that's not necessarily the case. Are you sure the editor you're
opening the file with can copy with the UCS-2 encoding?
but then I have done:

2)

byte[]content= System.Text.UnicodeEncoding.Unicode.GetBytes(string1);

//System.IO.FileStream wr=new //System.IO.FileStream("C:\\myhtml.html"
,System.IO.FileMode.CreateNew);

//wr.Write(content,0,content.Length);

//wr.Close();

System.IO.StreamWriter tr=new System.IO.StreamWriter("C:\\myhtml.html"
,,false,System.Text.Encoding.Unicode);

string teststr=System.Text.Encoding.Unicode.GetString(content);

tr.Write(teststr);//(I did not simply used string1 in it because of reason
of testing)

And file was in good form, why first time wasn't good as second?

The first probably didn't emit a byte order mark (BOM) whereas the
second one might have done. I suggest you look at the difference with a
binary file editor. If I'm write, the second file will have the bytes
0xFF 0xFE (or 0xFE 0xFF - I can never remember the order off-hand) at
the start, whereas the first won't.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top