public void GenerateDetailFile()
{
if (!Directory.Exists(AppVars.IntegrationFilesLocation))
{
Directory.CreateDirectory(AppVars.IntegrationFilesLocation);
}
You need to write the columns from each DataRow. Currently you are writing the DataRow object that is dataRow.ToString() hence you get string name "System.Data.DataRow"
of dataRow in your file
foreach(DataRow row in table.Rows)
{
foreach(DataColumn column in table.Columns)
{
sw.WriteLine(row[column]);
}
}
There is no "natural" string representation for a DataRow. You need to write it out in whatever format you desire, i.e., comma-separated list of values, etc. You can enumerate the columns and print their values, for instance:
foreach (DataRow row in table.Rows)
{
bool firstCol = true;
foreach (DataColumn col in table.Columns)
{
if (!firstCol) sw.Write(", ");
sw.Write(row[col].ToString());
firstCol = false;
}
sw.WriteLine();
}
Try this:
To write the DataTable rows to text files in the specific directory
var dir = @"D:\New folder\log"; // folder location
if (!Directory.Exists(dir)) // if it doesn't exist, create
Directory.CreateDirectory(dir);
foreach (DataRow row in dt.Rows)
{
for (int i = 0; i < dt.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == dt.Columns.Count - 1 ? "\n" : ",");
}
result.AppendLine();
}
string path = System.IO.Path.Combine(dir, "item.txt");
StreamWriter objWriter = new StreamWriter(path, false);
objWriter.WriteLine(result.ToString());
objWriter.Close();
When you try to print out a DataRow
like that, it is calling Object.ToString(), which simply prints out the name of the type. What you want to do is something like:
sw.WriteLine(String.Join(",", row.ItemArray));
This will print a comma separated list of all of the items in the DataRow
.
Something like:
sw.WriteLine(row["columnname"].ToString());
would be more appropriate.
The below code will let you to write text file each column separated by '|'
foreach (DataRow row in dt.Rows)
{
object[] array = row.ItemArray;
for (int i = 0; i < array.Length - 1; i++)
{
swExtLogFile.Write(array[i].ToString() + " | ");
}
swExtLogFile.WriteLine(array[array.Length - 1].ToString());
}
Reference link