Reputation: 4657
I have this code:
string s = "آ";
StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8);
writer.WriteLine(s);
but when I run it I can't see any "آ" in a.txt!! There isn't any string in a.txt! It is Empty! What is problem!?! Can anyone help me???
Upvotes: 12
Views: 41218
Reputation: 113
If you want to read a file from somewhere that contains these Unicode characters then you do some modifications and write back to the file, the problem arises. I was stuck with the same problem. Here is the solution that worked for me
Reading data from a file that contains Unicode characters
List<string>fileData= File.ReadAllLines("URPath",Encoding.Default).ToList());
//Any modifications
File.WriteAllLines("URPath", hstFileData,Encoding.Default);
I know this is not pretty but it worked. hope this helps!
Upvotes: 0
Reputation: 485
Follow, complete function for export a listview to excel with correct special characteres:
private void Exportar()
{
Encoding encoding = Encoding.UTF8;
saveFileDialog1.Filter = "Arquivo Excel (*.xls)|*.xls";
saveFileDialog1.FileName = "logs";
saveFileDialog1.Title = "Exportar para Excel";
StringBuilder sb = new StringBuilder();
foreach (ColumnHeader ch in lstPesquisa.Columns)
{
sb.Append(ch.Text + "\t");
}
sb.AppendLine();
foreach (ListViewItem lvi in lstPesquisa.Items)
{
foreach (ListViewItem.ListViewSubItem lvs in lvi.SubItems)
{
if (lvs.Text.Trim() == string.Empty)
{
sb.Append(" ");
}
else
{
string ITEM = Regex.Replace(lvs.Text, @"\t|\n|\r", "");//remover novas linhas
sb.Append(ITEM + "\t");
}
}
sb.AppendLine();
}
DialogResult dr = saveFileDialog1.ShowDialog();
if (dr == DialogResult.OK)
{
StreamWriter sw = new StreamWriter(saveFileDialog1.FileName, false, Encoding.UTF32);
sw.Write(sb.ToString());
sw.Close();
}
}
Upvotes: 0
Reputation: 6451
By the looks of it you're not Flush()
ing or Close()
ing the StreamWriter
before you end your application. StreamWriter
uses a buffer internally which needs to be flushed before you close your application or the StreamWriter
goes out of scope otherwise the data you wrote to it will not be written to disc.
You can call Close()
once you're done - although instead I would suggest using a using
statement instead to also assure that your StreamWriter
gets properly disposed.
string s = "آ";
using (StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
writer.WriteLine(s);
}
Upvotes: 5
Reputation: 6911
Few tips:
Check How to: Write Text to a File
Upvotes: 0
Reputation: 498904
You never Close()
the StreamWriter
.
If you call writer.Close()
when you finish writing, you will see the character.
But, since it implements IDisposable
you should wrap the creation of the StreamWriter
in a using
statement:
using(StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
writer.WriteLine(s);
}
This will close the stream for you.
Upvotes: 33