Custom checking file name on SaveFileDialog - c#

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?

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
}

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...

Related

C# Button with DialogResult Retry

I'm going to use two buttons that have a DialogResult Retry. When you push the button the winform will hide, do something and it pops-up again. I use the While method for this. But if you have two buttons with a retry this won't work unless you set one button DialogResult to Yes and do a While method. But is there a better way to do this, case switch or something?
Note this is within a Class
try
{
// Create a form to select objects.
DialogResult result = System.Windows.Forms.DialogResult.None;
while (result == DialogResult.None || result == DialogResult.Retry)
{
// Picking Objects.
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
var dialogResult = saveFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
string address = "http://www.autodesk.com/revit-basic-sample-family-2017-enu?_ga=2.28765692.1750602280.1538397390-459409917.1521646598";
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(address, saveFileDialog1.FileName);
Autodesk.Revit.DB.Family family = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Load Family");
if (doc.LoadFamily(saveFileDialog1.FileName, out family))
{
String name = family.Name;
TaskDialog.Show("Revit", "Family file " + name + " has been loaded ");
}
else
{
TaskDialog.Show("Revit", "Can't load the family file or already exists.");
}
tx.Commit();
}
}
if (dialogResult == DialogResult.Cancel)
{
}
}
// Show the dialog.
using (testForm selectionForm = new vuurenForm(commandData))
{
result = selectionForm.ShowDialog();
}
}
return Result.Succeeded;
You may set the DialogResult in the code, not in the form designer. Just double click the buttons and add something like:
private void button1_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Retry;
}
That way both buttons will have the same DialogResult.
Than the loop is OK with only checking for the DialogResult.Retry.
Exactly you can try this code to manage your DialogResult like:
switch(MessageBox.Show("Text", "Title", MessageBoxButtons.YesNo))
{
case DailogResult == DialogResult.Yes:
//Do something
case DailogResult == DialogResult.Retry:
//Do something
}
Actually for two Button objects you have to have two event-handler objects and you can set:
DialogResult = DialogResult.Retry;
In the event that you want to Retry.
You can try this:
var dialogResult = DialogResult.Retry;
while (dialogResult == DialogResult.Retry) {
try {
CheckSomething();
break;
}
catch {
if (dialogResult == DialogResult.Abort) {secondDialog.DialogResult = Retry;}
throw;
}
}
You can also use enums like below:
enum Result {Ignore, Abort,Retry};

C# Winform Retry

I have a problem with a Retry form. With this Form, I'm able to load a file from the internet. When it's done the main form pops up again. So far so good.
But when the user presses cancel, the save dialog pops up again. But what I want when the user presses the cancel button, he returns to the main form.
It Should be in this part, I think:
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return Result.Cancelled;
}
This is a part of my code:
try
{
// Create a form to select objects.
DialogResult result = System.Windows.Forms.DialogResult.None;
while (result == DialogResult.None || result == DialogResult.Retry)
{
// Picking Objects.
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string address = "http://www.autodesk.com/revit-basic-sample-family-2017-enu?_ga=2.28765692.1750602280.1538397390-459409917.1521646598";
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.DownloadFile(address, saveFileDialog1.FileName);
}
Autodesk.Revit.DB.Family family = null;
using (Transaction tx = new Transaction(doc))
{
tx.Start("Load Family");
if (doc.LoadFamily(saveFileDialog1.FileName, out family))
{
String name = family.Name;
TaskDialog.Show("Revit", "Family file " + name + " has been loaded " );
}
else
{
TaskDialog.Show("Revit", "Can't load the family file or already exists.");
}
tx.Commit();
}
if (saveFileDialog1.ShowDialog() == DialogResult.Cancel)
{
return Result.Cancelled;
}
}
// Show the dialog.
using (pickForm selectionForm = new pickForm(commandData))
{
result = selectionForm.ShowDialog();
}
}
return Result.Succeeded;
Everytime you call saveFileDialog1.ShowDialog() the dialog is opened. You need to store the result of the call for later checks:
if (result == DialogResult.Retry)
{
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.FileName = "test";
saveFileDialog1.Filter = "Family Files (*.rfa)|*.rfa|All Files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
// store result of the dialog
var dialogResult = saveFileDialog1.ShowDialog();
if (dialogResult == DialogResult.OK)
{
// ...
}
// ...
// compare the result without opening the dialog again.
if (dialogResult == DialogResult.Cancel)
{
return Result.Cancelled;
}
I think you can easily use if ... else statement for this like below :
System.Windows.Forms.SaveFileDialog saveFileDialog1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// your code
}
else // For Cancel
{
return Result.Cancelled;
}

C# Prompt to warn user of overwriting .txt file

Not sure how to implement this, i am not using SaveFileDialog which i have seen uses OverWritePrompt = true cant seem to get that to work for me.
I am using WPF.
The structure:-
I have a textBox called filePathBox - This contains a file path used from opening an: OpenFileDialog
private void fileBrowser_Click(object sender, RoutedEventArgs e)
{
//Firstly creating the OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
//Setting the filter for the file extension of the files as well as the default extension
dlg.DefaultExt = ".txt";
dlg.Filter = "All Files|*.*";
//Display the dialog box by calling the ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
//Grab the file you selected and display it in filePathBox
if (result == true)
{
//Open The document
string filename = dlg.FileName;
filePathBox.Text = filename;
}
}
You can then click a button and the .txt file displays in a textBox called textResult
private void helpfulNotes_Click(object sender, RoutedEventArgs e)
{
if (File.Exists(filePathBox.Text) && System.IO.Path.GetExtension(filePathBox.Text).ToLower() == ".txt")
{
textResult.Text = File.ReadAllText(filePathBox.Text);
}
if (string.IsNullOrWhiteSpace(filePathBox.Text))
{
MessageBox.Show("Please choose a file by clicking on the folder Icon :(");
}
}
Once you have made changes to that text in 'textResult' i have a button to save the text back to the file path that was originally loaded using the OpenFileDialog
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
At the moment it all saves fine, only it doesn't prompt the user saying are you sure you want to overwrite the file.
At the moment i could
load a file for the purpose of this named TestNote.txt into the
filePathBox
Type some text in textResult before even clicking to display the
file
Click save and it would just overwrite TestNote.txt with the text i
just entered without even warning me
Hopefully i have explained this adequately and provided all the code you need
Just add a messagebox to show your alert message before writing to the text file.
private void saveText_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(textResult.Text))
{
saveText.IsEnabled = false;
MessageBox.Show("No Text to save!");
}
else
{
if(MessageBox.Show("are you sure you want to overwrite the file.", "Alert", MessageBoxButtons.YesNo)==DialogResult.Yes)
{
saveText.IsEnabled = true;
string test = textResult.Text;
System.IO.File.WriteAllText(filePathBox.Text, test);
}
}
//fileSaveIcon.Visibility = Visibility.Visible;
//fileChangedIcon.Visibility = Visibility.Hidden;
}
Well, OverWritePrompt is a SaveFileDialog property, which you're not using: you're always using File.WriteAllText(), which always overwrites the target file.
You want to provide a Save function that saves an earlier opened file without prompt, a Save As function that prompts the user for a new filename and also call Save As when saving a new file.
This is implemented like this, pseudo:
private string _currentlyOpenedFile;
public void FileOpen_Click(...)
{
var openFileDialog = new ...OpenFileDialog();
if (openFileDialog.ShowDialog())
{
// Save the filename when opening a file.
_currentlyOpenedFile = openFileDialog.FileName;
}
}
public void FileNew_Click(...)
{
// Clear the filename when closing a file or making a new file.
_currentlyOpenedFile = null;
}
public void FileSave_Click(...)
{
if (_currentlyOpenedFile == null)
{
// New file, treat as SaveAs
FileSaveAs_Click();
return;
}
}
public void FileSaveAs_Click(...)
{
var saveFileDialog = new ...SaveFileDialog();
if (openFileDialog.ShowDialog())
{
// Write the file.
File.WriteAllText(text, openFileDialog.FileName);
// Save the filename after writing the file.
_currentlyOpenedFile = openFileDialog.FileName;
}
}
Here you'll be leveraging the SaveFileDialog's functionality which prompts the user whether they want to overwrite an already existing file.

How to restrict special characters in File Dialog's file name in C#?

My scenario is, need to restrict the selection of file in an OpenFileDialog, when there exists any special characters like #,%,+, -.
I can validate the file name after selecting file by the following code.
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
if(dlg.SafeFileName.Contains("#") || dlg.SafeFileName.Contains("+")
{
// show error message;
// Open file dialog again;
}
}
Is there any way to validate the file name without closing the dialog?
Thanks in advance.
I dont't know what kind of FileDialog you are using but assuming it's an OpenFileDialog, here's something you can do.
OpenFileDialog dlg;
public Form1()
{
InitializeComponent();
dlg = new OpenFileDialog();
dlg.FileOk += dlg_FileOk;
}
void dlg_FileOk(object sender, CancelEventArgs e)
{
if (dlg.SafeFileName.Contains("#") || dlg.SafeFileName.Contains("+"))
{
e.Cancel = true;
// show error message;
}
}
You can use the "FileOk" event. When you press "Save" in your SaveFileDialogue, the FileOk event is triggered. You can then stop the closing of the dialogue.
Here is an example:
public void CallDialogue()
{
var sfd = new SaveFileDialog();
sfd.FileOk += ValidateName;
if (sfd.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(sfd.FileName);
}
}
private void ValidateName(object sender, CancelEventArgs e)
{
var sfd = sender as SaveFileDialog;
var file = new FileInfo(sfd.FileName);
if (file.Name.Contains('#'))
e.Cancel = true;
// i did the FileInfo Stuff to quickly extract ONLY the file name,
// without the full path. Thats optional of course. Just an example ;-)
}
Just for illustration, you can also put the validation inline if you want:
using System;
using System.Windows.Forms;
namespace ConsoleApplication2
{
class Program
{
[STAThread]
private static void Main()
{
using (var dialog = new SaveFileDialog())
{
dialog.FileOk += (sender, args) =>
{
var dlg = (FileDialog) sender;
if (dlg.FileName.IndexOfAny("+#%-".ToCharArray()) < 0)
return;
MessageBox.Show("Invalid character in filename: " + dlg.FileName);
args.Cancel = true;
};
dialog.ShowDialog();
}
}
}
}

How can I prevent an exception when I cancel an openfiledialog?

My program has a button which when clicked opens an openfiledialog to choose a picture:
private string ChoosePicture()
{
fDialog.Title = "Select Picture";
fDialog.Filter = "Image Files (*.bmp, *.gif, *.jpg)|*.bmp; *.gif*;*.jpg";
fDialog.InitialDirectory = "C:";
fDialog.ShowDialog();
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
//returns a string for the directory
return fDialog.FileName.ToString();
}
Using a check on the dialogresult box hasn't resolved my issue either:
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
DialogResult res = fDialog.ShowDialog();
if (res == DialogResult.OK)
{
//returns a string for the directory
return fDialog.FileName.ToString();
}
return null;
The code works if I do choose a picture and complete the file selection. However if I cancel the process at any point in between I get the exception "The path is not of a legal form". I am not sure which part I imagine I could take care of this with a try-catch, however I'm not positive which part is causing the issue? If I put a try catch around the call to the ChoosePicture() method, I can at least stop it from crashing the program but the exception is still being thrown when no picture is selected in the fdialogbox.
DialogResult result = fileDialog.ShowDialog();
if (result == DialogResult.OK) {
//returns a string for the directory
return fDialog.FileName;
}
return null; //not sure what you will return if they cancel
also, FileName is already a string, so no need to use .ToString() on it
EDIT: fixed indenting
Check the dialog result and act accordingly:
private string ChoosePicture()
{
fDialog.Title = "Select Picture";
fDialog.Filter = "Image Files (*.bmp, *.gif, *.jpg)|*.bmp; *.gif*;*.jpg";
fDialog.InitialDirectory = "C:";
DialogResult res = fDialog.ShowDialog();
if(res == DialogResult.OK)
{
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
//returns a string for the directory
return fDialog.FileName.ToString();
}
else
{
return null; // or something
}
}
Test to see if a file was selected:
fDialog.ShowDialog();
if (!string.IsNullOrEmpty(fDialog.FileName))
{
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
//returns a string for the directory
return fDialog.FileName.ToString();
} else {
return String.Empty;
}
DialogResult dresult=fDialog.ShowDialog();
Check if dresult==DialogResult.Ok and only after proceed with file operations.
fDialog.AddExtension = true;
fDialog.CheckFileExists = true;
fDialog.CheckPathExists = true;
DialogResult res = fDialog.ShowDialog();
if (res == DialogResult.OK)
{
//returns a string for the directory
return fDialog.FileName.ToString();
}
return null;
Now it will work !
We should add properties to the dialogbox before its actually been shown. So when it opens, it will have all these properties when you open them for the first time.
Edit :okay you have added to the designer by the toolbox already and its by default all of these options. but if some add from code. it should be always before its being shown. I will leave this here. so that someone who does this
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
in code, will know that they should do these property addition before showing the dialog. Again, these true values are by default so unless u have mentioned false before elsewhere and making it true here.
You can just do it like this instead of return fDialog.FileName; and DialogResult.Cancel is a better option since your looking for a cancel and not for the OK result.
DialogResult result = fDialog.ShowDialog();
if (result == DialogResult.Cancel)
{
return;
}
i added a boolean and check if file selected or not
public Form1()
{
InitializeComponent();
}
bool fileSelected = false; //default false because nothing selected at start.
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
openFile();
if (fileSelected == true)
{
codes...
}
}
string path= "";
private void openFile()
{
OpenFileDialog file= new OpenFileDialog();
file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
file.Filter = "Text File|*.txt";
//file.RestoreDirectory = true;
if (file.ShowDialog() == DialogResult.OK)
{
path= dosya.FileName;
fileSelected = true;
}
else
{
MessageBox.Show("File not selected.");
}
}
i prevent this error like that.

Categories