Home > other >  Return the pathname after saving file using saveFileDialog - C#
Return the pathname after saving file using saveFileDialog - C#

Time:01-26

I am creating and saving a csv file using saveFileDialog. I need to find a way to remember the pathName that the person saves the file to so that I can use the pathName to the file later on in the code.

The below code is what I have been trying, just to return the pathName but it will actually only be returning the sfd.FileName. Is there a way to get the full path?

 private void saveCSVbutton_Click(object sender, EventArgs e)
    {
        saveShipping();
        saveATT();
        saveVerizon();

        String shippingPath = saveShipping();
        MessageBox.Show(shippingPath);    
}  
private String saveShipping()
    {
        if (dataGridView1.Rows.Count > 0)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "CSV (*.csv)|*.csv";
            sfd.FileName = "shippingOutput.csv";
            bool fileError = false;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                if (File.Exists(sfd.FileName)) 
                {
                    try
                    {//overwrite file
                        File.Delete(sfd.FileName);
                    }
                    catch (IOException ex)
                    {
                        fileError = true;
                        MessageBox.Show("It wasn't possible to write the data to the disk."   ex.Message);
                    }
                }
                if (!fileError)
                {
                    try
                    {
                        int columnCount = dataGridView1.Columns.Count;
                        string columnNames = "";
                        string[] outputCsv = new string[dataGridView1.Rows.Count   1];
                        for (int i = 0; i < columnCount; i  )
                        {
                            columnNames  = dataGridView1.Columns[i].HeaderText.ToString()   ",";
                        }
                        outputCsv[0]  = columnNames;

                        for (int i = 1; i < dataGridView1.Rows.Count; i  )
                        {
                            for (int j = 0; j < columnCount; j  )
                            {
                                outputCsv[i]  = dataGridView1.Rows[i - 1].Cells[j].Value.ToString()   ",";
                            }
                        }

                        File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
                        MessageBox.Show("Data Exported Successfully", "Info");
                        String attachPathName = sfd.FileName;
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("Error :"   ex.Message);
                    }
                }
            }
        }
        else
        {
            MessageBox.Show("No Record To Export", "Info");
        }
        return attachPathName;
    }

CodePudding user response:

There are 2 ways that I can think of that would keep it simple for you but they both kindoff work the same way, It depends on your requirements. I will just call it Method 1 and 2.

Method 1.

Preslave Tsenov has a good answer to keep it straight forward, However I noticed your SaveFileDialogue sfd variable is being Declared and Instantiated from within the method. So in short you will not be able to access it from outside the method block.

If you move the variable to just above the Constructor and declare it as Public(You want access to the variable from inside and outside the class) or as Private(You only want access to the variable from within your class). Once you have done that you should be able to call the variable at any moment.

Your code would then look something like this

public SaveFileDialog sfd = new SaveFileDialog();

private void saveCSVbutton_Click(object sender, EventArgs e)
{
    saveShipping();
    saveATT();
    saveVerizon();

    String shippingPath = saveShipping();
    MessageBox.Show(shippingPath);    
}  
private String saveShipping()
{
    if (dataGridView1.Rows.Count > 0)
    {
        sfd.Filter = "CSV (*.csv)|*.csv";
        sfd.FileName = "shippingOutput.csv";
        bool fileError = false;
        if (sfd.ShowDialog() == DialogResult.OK)
        {
            if (File.Exists(sfd.FileName)) 
            {
                try
                {//overwrite file
                    File.Delete(sfd.FileName);
                }
                catch (IOException ex)
                {
                    fileError = true;
                    MessageBox.Show("It wasn't possible to write the data to the disk."   ex.Message);
                }
            }
            if (!fileError)
            {
                try
                {
                    int columnCount = dataGridView1.Columns.Count;
                    string columnNames = "";
                    string[] outputCsv = new string[dataGridView1.Rows.Count   1];
                    for (int i = 0; i < columnCount; i  )
                    {
                        columnNames  = dataGridView1.Columns[i].HeaderText.ToString()   ",";
                    }
                    outputCsv[0]  = columnNames;

                    for (int i = 1; i < dataGridView1.Rows.Count; i  )
                    {
                        for (int j = 0; j < columnCount; j  )
                        {
                            outputCsv[i]  = dataGridView1.Rows[i - 1].Cells[j].Value.ToString()   ",";
                        }
                    }

                    File.WriteAllLines(sfd.FileName, outputCsv, Encoding.UTF8);
                    MessageBox.Show("Data Exported Successfully", "Info");
                    String attachPathName = sfd.FileName;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error :"   ex.Message);
                }
            }
        }
    }
    else
    {
        MessageBox.Show("No Record To Export", "Info");
    }
    return attachPathName;
}

Method 2 You could create a new class called "SessionVariables.cs" and a "SaveFileDialog sfd = new SaveFileDialog();" variable and declare it as public. You can then get and set the value at any anytime.

I have seen a few developers use this method, Specifically VB developers but it still works in C#. Just remember not to instantiate a new SaveFileDialog every time you use it or else the values will get cleared every time.

I hope this works for you or at least got you closer to a solution.

CodePudding user response:

You can use Path.GetDirectoryName(sfd.FileName) to get full path to the file

  •  Tags:  
  • Related