我正在从 SQL 数据库中检索数据并将其保存为“.txt”作为逗号分隔的文件,使用 Web 应用程序作为开发环境。我唯一的问题是在第一列的开头它添加了一些垃圾字符。
前任。¼¤日期、时间
尝试使用Encoding.ASCII
和新UTF8Encoding(false)
的但解决了这个错误。
但是其余的数据是完美的。下面的代码是用于保存数据的代码。
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();