public void GenerateDetailFile()
{
if (!Directory.Exists(AppVars.IntegrationFilesLocation))
{
Directory.CreateDirectory(AppVars.IntegrationFilesLocation);
}
DateTime DateTime = DateTime.Now;
using (StreamWriter sw = File.CreateText(AppVars.IntegrationFilesLocation +
DateTime.ToString(DateFormat) + " Detail.txt"))
{
DataTable table = Database.GetDetailTXTFileData();
foreach (DataRow row in table.Rows)
{
sw.WriteLine(row);
}
}
}
Not sure what I'm missing here but I think it might be the column name which I'm not sure how to set it up.
This is working fine, except, when it writes to the text file, it's writing this:
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
System.Data.DataRow
Can anyone give me a hand?
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();
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();
}
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
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]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With