Reputation: 23
I am using SaveFileDialog
in my application. Is there a way to get the folder path selected by the user before actually saving the file? I know that I can get the folder path after the file is saved but I need the folder path before the file is saved. I need to use the folder name to set the file name e.g. if the user selects the folder called "ABC", the file name in "File name" textbox is set to "ABC10001" and the next file will be "ABC10002" etc.
I know that I can use FolderBrowserDialog but I don't really like the UI. I would also like to give an option to the user to overwrite the file name which is not possible with FolderBrowserDialog.
private void Button_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = @"C:\";
saveFileDialog.Title = "Save text Files";
saveFileDialog.CheckFileExists = true;
saveFileDialog.CheckPathExists = true;
saveFileDialog.DefaultExt = "txt";
saveFileDialog.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog.FilterIndex = 2;
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string folderPath = Path.GetDirectoryName(saveFileDialog.FileName);
}
}
Any help would be appreciated.
Thanks in advance.
Upvotes: 2
Views: 1771
Reputation: 23
Here is the working code:
[STAThread]
static void Main(string[] args)
{
CommonSaveFileDialog saveFileDialog = new CommonSaveFileDialog();
saveFileDialog.FolderChanging += SaveFileDialog_FolderChanging;
saveFileDialog.ShowDialog();
}
private static void SaveFileDialog_FolderChanging(object sender, CommonFileDialogFolderChangeEventArgs e)
{
Console.WriteLine(e.Folder);
}
Upvotes: 0
Reputation: 60
SaveFileDialog
only supports selecting a file, not a folder. However after getting the DialogResult
from calling SaveFileDialog.ShowDialog()
, you can use Path.GetDirectoryName()
on SaveFileDialog.FileName
to retrieve the folder name.
Alternatively you can use the CommonOpenFileDialog
from WindowsAPICodePack package to allow users to select a folder.
Upvotes: 3