这是一个可以正常工作并清理干净的版本。它摆脱了引起问题的更广泛的范围变量。它使用一种方式写入生成该文件的文件,因此您不必检测它是否已经存在。它将您的ROW1重命名为ROW2到实际上是它们的列。而且,它使您不必在每次写一行时都打开/关闭文件。
static void Main(string[] args)
{
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string dbFile = filePath + @"\sqlfile.txt";
writeFileFromDB(dbFile);
}
public static void writeFileFromDB(string dbFile)
{
//create connection
sqlCommand comm = new sqlCommand();
comm.Connection = new sqlConnection(@"MY DB CONNECTION STRING");
String sql = @"SELECT COLUMN1, COLUMN2
FROM Export.TABLENAME";
comm.CommandText = sql;
comm.Connection.open();
sqlDataReader sqlReader = comm.ExecuteReader();
// Open the file for write operations. If exists, it will overwrite due to the "false" parameter
using (StreamWriter file = new StreamWriter(dbFile, false))
{
while (sqlReader.Read())
{
file.WriteLine(sqlReader["COLUMN1"] + "\t" + sqlReader["COLUMN2"]);
}
}
sqlReader.Close();
comm.Connection.Close();
}