I am retrieving data from the SQL database and saving it ‘.txt’ as a comma delimited file using a Web Application as developing environment.
The only problem I have is that at the start of the first column it add some garbage characters.
Ex. ¼¤Date, Time
Tried to use Encoding.ASCII and new UTF8Encoding(false) but solved the bug.
But the rest of the data is perfect. The code below is the one used to save the data.
System.IO.StringWriter sWriter;
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sWriter = new System.IO.StringWriter(sb);
string Str;
for (int k = 0; k < (grdGridView.Columns.Count); k++)
{
if (k == (grdGridView.Columns.Count) - 1)
sWriter.Write(grdGridView.HeaderRow.Cells[k].Text);
else
sWriter.Write(grdGridView.HeaderRow.Cells[k].Text + ",");
}
sWriter.WriteLine("");
for (int i = 0; i < (grdGridView.Rows.Count); i++)
{
for (int j = 0; j < (grdGridView.Columns.Count); j++)
{
Str = (grdGridView.Rows[i].Cells[j].Text.ToString());
if (Str == " ")
Str = "";
if (j != (grdGridView.Columns.Count) - 1)
{ Str = (Str + ","); }
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
// Download File Directly to Web Server
//string HtmlInfo = sWriter.ToString().Trim();
string HtmlInfo = sWriter.ToString();
string DocFileName = fileName1 + ".txt";
string FilePathName = Server.MapPath("~/Download");
FilePathName = FilePathName + "\\" + DocFileName;
File.Delete(FilePathName);
FileStream Fs = new FileStream(FilePathName, FileMode.Create);
BinaryWriter BWriter = new BinaryWriter(Fs, Encoding.GetEncoding("UTF-8"));
BWriter.Write(HtmlInfo);
BWriter.Close();
Fs.Close();
Using a BinaryWriter makes little sense here. The characters you see are the Length-prefix that is prependeded to a string by a BinaryWriter.
Use a TextWriter instead, or get the contents of sWriter as a
byte[].