Monday, May 25, 2009

Write TextFile from SQLDataReader

public static void mWriteTextFileFromSQLDataReader(SqlDataReader rd, string strTextFilePath)
{
using (FileStream fs = new FileStream(strTextFilePath, FileMode.Create, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.Unicode))
{
while (rd.Read())
{

for (int i = 0; i < rd.VisibleFieldCount; i++)
{
if (!rd.IsDBNull(i))
{
switch (rd.GetDataTypeName(i))
{
case "NUMBER":
sw.Write(rd.GetInt32(i).ToString());
break;
case "DATE":
sw.Write(rd.GetDateTime(i).ToString("MM/dd/yyyy HH:mm:ss"));
break;
case "VARCHAR2":
sw.Write(rd.GetString(i));
break;
default:
sw.WriteLine(rd.GetValue(i).ToString());
break;
}

if (i < rd.VisibleFieldCount) // Between DataFields
sw.Write("\t");


}
}

sw.WriteLine(); // Between Records
}
}
}
}

No comments:

Post a Comment

 
Locations of visitors to this page