how to convert a UTF8 string to Unicode with C#

G

Guest

Dear all,

I use streamreader to read a file line by line. However, both UTF8 and
Unicode exists in each line. Is there a way to convert a substring's encoding of a string there is came from streamreader? Here is my code:

private String searchChapter(string book, string chap, string filePath)
{

String Chapter = "";

try
{

// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(filePath))
{

// Read and display lines from the file until the end of
// the file is reached.
int colonIdx;
String line;
bool isFound = false;

//testing
Chapter = sr.CurrentEncoding.ToString() + "\r\n\r\n";

while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
colonIdx = line.IndexOf(":");
if (line.Substring(0,3) == book && line.Substring(4,colonIdx - 4) == chap)
{
isFound = true;


}

Chapter = Chapter + line + "\r\n\r\n";


}
else if (isFound == true) break;
}
}
return Chapter;
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
return Chapter;
}
 
J

Jon Skeet [C# MVP]

Kempton said:
I use streamreader to read a file line by line. However, both UTF8 and
Unicode exists in each line.

In that case, you basically can't use StreamReader - or at least, I
wouldn't recommend doing so.

Is this a file from a source you can change? It sounds like a *really*
bad idea to me, changing encoding half way through a file, let alone a
line.
 
A

Alex Feinman [MVP]

I think you are mistaken. I can hardly imagine a document combining UTF-8
and Unicode in the same line. Could you post an example of your text -
perhaps in hex format?

--
Alex Feinman
---
Visit http://www.opennetcf.org
Kempton said:
Dear all,

I use streamreader to read a file line by line. However, both UTF8 and
Unicode exists in each line. Is there a way to convert a substring's
encoding of a string there is came from streamreader? Here is my code:
 

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