-1

I need to write the content of a DataTable to a csv. There are some Chinese strings in it as well.

I used to use the below script:

System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(dlg.FileName);

string strHeader = "";
for (int s = 0; s < table.Columns.Count; s++)
{
    strHeader += table.Columns[s].ColumnName + ",";
}
streamWriter.WriteLine(strHeader);

for (int m = 0; m < table.Rows.Count; m++)
{
    string strRowValue = "";
    for (int n = 0; n < table.Columns.Count; n++)
    {
        strRowValue += table.Rows[m][n] + ",";
    }
    streamWriter.WriteLine(strRowValue);
}
streamWriter.Close();

But that obviously doesn't handle Unicode characters. It writes instead something like æœç‹—. So I tried to set the encoding like this:

System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(dlg.FileName, Encoding.UTF8);

But then I get Argument 1: cannot convert from 'string' to 'System.IO.Stream. So how could I set the encoding in this very example?

fishmong3r
  • 1,414
  • 4
  • 24
  • 51
  • 4
    Have you tried reading the [documentation for StreamWriter](https://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx)? – Albireo Dec 17 '15 at 10:35
  • Or searched StackOverflow for an answer: for example http://stackoverflow.com/questions/373365/how-to-write-out-a-text-file-in-c-sharp-with-a-code-page-other-than-utf-8 – Alex Dec 17 '15 at 10:38
  • 1
    Also note that the constructor in your original code defaults to using UTF-8 anyway... so I dispute your claim that "that obviously doesn't handle Unicode characters". It's not clear where the problem is. You should also learn about `using` statements and either `StringBuilder` or just calling `Write` rather than concatenating strings in a loop. – Jon Skeet Dec 17 '15 at 10:38
  • @Albireo Yes, I have tried. :) – fishmong3r Dec 17 '15 at 10:42
  • What's the problem with [`StreamWriter Constructor (String, Boolean, Encoding)`](https://msdn.microsoft.com/en-us/library/f5f5x7kt.aspx) then? – Albireo Dec 17 '15 at 10:45

1 Answers1

9
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(new FileStream(dlg.FileName, FileMode.Open), Encoding.UTF8);
Alexcei Shmakov
  • 2,203
  • 3
  • 19
  • 34