How to save files to a particular directory using Savefiledialog in c#. The path user should not change the directory when savefile dialog is opened.
-
SaveFileDialog control is meant to let the user choose the path and display particular file types. And note that it won't perform the actual "save" method. I think you are misusing it. – etaiso Mar 06 '14 at 10:59
1 Answers
There is no direct way (a property like KeepSameFolder=True
for example).
Your only option is to write an event handler for the FileOK event and cancel the click on the Save button if the folder is not the one you like.
Cancelling the event doesnt't close the SaveFileDialog and the user could fix its error
// declare at the global class level
string allowedPath = @"c:\temp";
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
if (!Path.GetDirectoryName(openFileDialog1.FileName) == allowedPath )
{
MessageBox.Show("You should save your file in or a sub folder of: " + allowedPath);
e.Cancel = true;
}
}
EDIT: Following the comment of Mr Hofman, if you allow a subfolder of your base path to be choosen then you should change the check inside the event handler to something like
string userChoice = Path.GetDirectoryName(openFileDialog1.FileName);
if (!userChoice.StartsWith(allowedPath))
{
MessageBox.Show("You should save your file in the folder: " + allowedPath);
e.Cancel = true;
}
However, as said in the comments above, I think that using a SaveFileDialog when the user has no option on where he/she wants to save its file is not a good choice. If the folder is predefined then just prepare a reusable InputForm that asks for just the file name and build your full filename in code.
-
1Thanks. I think this post now adds something above the duplicate question. – Patrick Hofman Mar 06 '14 at 11:11