bob
bob

Reputation: 7

How do i save my CSV file to a location for the user to select?

Hi i have searched for this codes that create a csv file but this only works by indicating a default location. How should i do if i would like to define the file location?

    private void btnExport_Click(object sender, EventArgs e)
{
    //Build the CSV file data as a Comma separated string.
    string csv = string.Empty;

    //Add the Header row for CSV file.
    foreach (DataGridViewColumn column in dataGridView1.Columns)
    {
        csv += column.HeaderText + ',';
    }

    //Add new line.
    csv += "\r\n";

    //Adding the Rows
    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
        foreach (DataGridViewCell cell in row.Cells)
        {
            //Add the Data rows.
            csv += cell.Value.ToString().Replace(",", ";") + ',';
        }

        //Add new line.
        csv += "\r\n";
    }

    //Exporting to CSV.
    string folderPath = "C:\\CSV\\";
    File.WriteAllText(folderPath + "DataGridViewExport.csv", csv);
}

Upvotes: 0

Views: 2161

Answers (1)

ainwood
ainwood

Reputation: 1048

Use the SaveFileDialog

SaveFileDialog dialog = new SaveFileDialog();
DialogResult result = dialog.ShowDialog();
string selectedPath = "";
if (result == DialogResult.OK)
{
    selectedPath = dialog.FileName;
}

You can select options like the start directory etc, but overall it's pretty easy to use.

Upvotes: 4

Related Questions