export to CSV from datagridview with date format

denesh neupane 121 Reputation points
2022-03-07T06:51:16.397+00:00

i want to save the datagridview data to CSV but dont know the idea to chang the date format from 2022/03/07 00:00 to
2022/03/07.

 private void button7_Click(object sender, EventArgs e)
    {

    try
         {
             string csv = string.Empty;
             string HeaderText = string.Empty;
            foreach (DataGridViewColumn column in tableDataGridView.Columns)
                {
                    csv += column.HeaderText + ',';

                }
                csv += "\r\n";
                foreach (DataGridViewRow row in tableDataGridView.Rows)
                {
                   foreach (DataGridViewCell cell in row.Cells)
                       {
                           if (cell.Value != null)

                            {

          csv += cell.Value.ToString()/*.TrimEnd(',')*//*.Replace(",", ";") */+ /*','*/",";


                        }

                    }
                    csv += "\r\n";
                }


                string folderPath = "C:\\CSV\\";
                if (!Directory.Exists(folderPath))
                {
                    Directory.CreateDirectory(folderPath);
                }

                {


                 File.WriteAllText(folderPath + DateTime.Now.ToString("yyyyMMdd_HH-mm-ss") + ".csv", csv, Encoding.UTF8);


                    textBox3.Text = "保存しました";
                    textBox3.BackColor = Color.Green;
                }
            }
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,385 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,131 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,311 Reputation points Microsoft Vendor
    2022-03-07T07:41:17.67+00:00

    @denesh neupane , based on my test, I suggest that you don't use 2022/03/07 the format in the path. Becuase windows limit that the file name can not contain the / character.
    You could check it manually as the following:

    180584-image.png
    If you still want to use datetime formart to name the path, I suggest that you could use the following code:

    File.WriteAllText(folderPath + DateTime.Now.ToString("yyyy-MM-dd") + ".csv", csv, Encoding.UTF8);  
    

    Like the following pic:

    180593-image.png


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful