0

I am writing some strings in an Excel file. Sometimes the call to the

StreamWriter.WriteLine()  

function unexpectedly creates a "Â" character.

Any idea why?

Update

the code:

StreamWriter writer = new StreamWriter(File.Create(outFile)); 
string headerline = ""; 
foreach (DataColumn colum in reportContents.Columns) 
{ 
    headerline = headerline + '"' + row[colum].ToString() + '"' + ',';
} 
writer.WriteLine(headerline);

the output: Personal Protection |Post-Retirement Savings|Pre-Retirement Pension|Tax & Estate Planning

Expected output: Personal Protection |Post-Retirement Savings|Pre-Retirement Pension|Tax & Estate Planning

I get the solution: just i need to specify the default the encoding in StreamWriter like as follows and it works.

StreamWriter writer = new StreamWriter(File.Create(outFile), Encoding.Default);

shuvra

Shuvra
  • 213
  • 2
  • 15

2 Answers2

3

It isn't actually creating an  character - it's just writing data in a different encoding. If you look at the StreamWriter constructor overloads (http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx) you can indicate which encoding you want the StreamWriter to write it's data in.

In case you haven't dealt with encoding before: Joel wrote a good article about it at http://www.joelonsoftware.com/articles/Unicode.html

C.Evenhuis
  • 25,996
  • 2
  • 58
  • 72
  • the code: StreamWriter writer = new StreamWriter(File.Create(outFile)); string headerline = ""; headerline = ""; foreach (DataColumn colum in reportContents.Columns) { headerline = headerline + '"' + row[colum].ToString() + '"' + ','; } writer.WriteLine(headerline); – Shuvra Jun 21 '11 at 14:10
  • I am not using any encoding. why this character will appear? the output is: Personal Protection |Post-Retirement Savings|Pre-Retirement Pension|Tax & Estate Planning – Shuvra Jun 21 '11 at 14:13
  • 1
    @Shuvra I updated your question with the code you posted in this comment. But YOU should have done that. – Adriano Carneiro Jun 21 '11 at 14:14
  • Whenever you store text, you are using encoding. I really suggest reading Joel's post I linked, to rid of this illusion for good. – C.Evenhuis Jun 21 '11 at 15:51
  • I get the solution: just i need to specify the default the encoding in StreamWriter like as follows and it works. StreamWriter writer = new StreamWriter(File.Create(outFile), Encoding.Default); shuvra – Shuvra Jun 21 '11 at 16:30
1

The character set of your code should be "utf-8".

Naveen
  • 119
  • 2
  • 4
  • 13