'Return the pathname after saving file using saveFileDialog - C#
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;
}
Solution 1:[1]
You can use Path.GetDirectoryName(sfd.FileName) to get full path to the file
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Preslav Tsenov |
