How do i convert unicode string to ansi string in C#?

J

Jon Skeet [C# MVP]

Mark Rae said:

I hate to say it, but the code on there is pretty awful.

Save byte array to a binary file:
1) No "using" statement to close the file if anything goes wrong.
(It may seem picky to state this for every example, but it's really,
really important.)
2) There's no need for a binary writer if you're just saving a byte
array! Just use Stream.Write.

Read a file into a byte array:
1) Again, no using statement
2) Again, no need for a binary reader
3) Assumes file length doesn't change after finding out length
See http://www.pobox.com/~skeet/csharp/readbinary.html for better code

Write ANSI strings to a text file:
1) No "using" statement
2) Doesn't use ANSI! Uses UTF-8 (the default encoding for StreamWriter)

Read UTF-8 file and display in textbox
1) No using statement
2) No need to explicitly use UTF-8 when that's the default!
3) Loading a file in the UI thread is a bad idea. Why even
bother making the example a GUI one? (The name of the method
is pretty terrible too.)

Writer string to UTF-8 encoded file:
1) No using statement
2) Again, why explicitly state UTF-8? (If it's because the
property is different from the version used by default,
that should be very clearly commented.)

Write Unicode File:
1) No using statement
2) Again, uses UI property while doing file IO. Generally not
a good idea, and again not needed for the example.

Seeking etc
1) No using statement
2) I far prefer the Position property to calling Seek when you're going
to a specific place in the file. I think it's much clearer. That's
possibly just me though.
3) Comment for calling Stream.Read says that 100 bytes are read, when
actually *up to* 100 bytes are read. This should be at least
mentioned, as it's the cause of frequent problems. At least the
return value is stored in a variable...

Copy a file
1) Again, IO in a UI thread...
2) What's wrong with a straight call to File.Copy?

Move/Rename, and Delete
See problems with copy
 
M

Mark Rae

I hate to say it, but the code on there is pretty awful.

Blimey - you're quite correct! I really need to sense-check the content of
other people's websites before suggesting them as useful references...
 

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