Reputation: 4417
I have a SaveFileDialog
.
When the user clicks on OK I have to check if there is a similar file name.
The system has been doing such a test, but I need to add a test Is there a file with a similar name and numbering.
For example, if the user selected a file name "a" and there is a file "a1" or "a2", warning message should appear. (as it appears when there is a file named "a").
Is there a way to do this?
Upvotes: 3
Views: 1429
Reputation: 2812
this is the answer you want
SaveFileDialog S = new SaveFileDialog();
if(S.ShowDialog() == DialogResult.OK)
{
bool ShowWarning = false;
string DirPath = System.IO.Path.GetDirectoryName(S.FileName);
string[] Files = System.IO.Directory.GetFiles(DirPath);
string NOFWE = DirPath+"\\"+System.IO.Path.GetFileNameWithoutExtension(S.FileName);
foreach (var item in Files)
{
if (item.Length > NOFWE.Length && item.Substring(0, NOFWE.Length) == NOFWE)
{
int n;
string Extension = System.IO.Path.GetExtension(item);
string RemainString = item.Substring(NOFWE.Length, item.Length - Extension.Length - NOFWE.Length);
bool isNumeric = int.TryParse(RemainString, out n);
if(isNumeric)
{
ShowWarning = true;
break;
}
}
}
if(ShowWarning)
{
if (MessageBox.Show("Warning alert!", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
Save();//Saving instance
}
else
{
Save();//Saving instance
}
}
ans Save()
method is the saving instructions...
Upvotes: 0
Reputation: 89285
SaveFileDialog
inherits FileDialog
class which has FileOk
event. You can put logic to check if similar files already exist in the handler method for this event. If the result is true
, display warning message. Then if user choose No
from the warning dialog, set Cancel
property of CancelEventArgs
parameter to True
, this will prevent save file dialog window from closing :
var dlg = new SaveFileDialog();
dlg.FileOk += (o, args) =>
{
var file = dlg.FileName;
if (isSimilarFileExist(file))
{
var result = MessageBox.Show("Similar file names exist in the same folder. Do you want to continue?",
"Some dialog title",
MessageBoxButtons.YesNo,
MessageBoxIcon.Warning
);
if(result == DialogResult.No)
args.Cancel = true;
}
};
dlg.ShowDialog();
......
private bool isSimilarFileExist(string file)
{
//put your logic here
}
Upvotes: 2