2
Answers

how to add timestamp for csv file using C#

Meghana M

Meghana M

1y
869
1

code:

string path=@"c:\file"; 

try{

command.CommandText = "dbo.SpSample";
                command.CommandType = CommandType.StoredProcedure;
                dataAdapter = new SqlDataAdapter(command.CommandText, connect);
                dataAdapter.Fill(dataSet, "dbo.SpSample");
                DataTable t2 = dataSet.Tables["dbo.SpSample"];

                string csv2 = string.Empty;

                foreach (DataColumn column in t2.Columns)
                {
                    csv2 += column.ColumnName + ',';
                }
                csv2 += "\r\n";
                foreach (DataRow row in t2.Rows)
                {
                    foreach (DataColumn column in t2.Columns)
                    {
                        csv2 += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                    }
                    csv2 += "\r\n";
                }
                File.WriteAllText(exportPath + DateTime.Now + "Sample1.csv", csv2);

}

catch (Exception e){}

code is working fine but if i add timestamp in file.writealltext method getting error 

timeformat(11/1/2023 12:00) should be like this

Answers (2)