Restore Last Directory for Open/Save Dialog Boxes separately - c#

I'm using Visual Studio, WPF, C#, XAML.
My program has Input and Output buttons.
Input uses OpenFileDialog.
Output uses SaveFileDialog.
I need each button to remember its last used directory, but RestoreDirectory = true causes both button's last directory to be the same. Each does not remember it's own directory separate.
// Input Button
//
private void btnInput_Click(object sender, RoutedEventArgs e)
{
// Open 'Select File' Window
Microsoft.Win32.OpenFileDialog selectFile = new Microsoft.Win32.OpenFileDialog();
// Remember Last Dir
selectFile.RestoreDirectory = true;
// Show Window
Nullable<bool> result = selectFile.ShowDialog();
// Display Path
if (result == true)
{
tbxInput.Text = selectFile.FileName;
}
}
// Output Button
//
private void btnOutput_Click(object sender, RoutedEventArgs e)
{
// Open 'Save File' Window
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
// Remember Last Dir
saveFile.RestoreDirectory = true;
// Show Window
Nullable<bool> result = saveFile.ShowDialog();
// Display Path
if (result == true)
{
tbxOutput.Text = saveFile.FileName;
}
}

Related

Winforms "Save" button (like we have in MS Word)

My point is to create a save button like we have in Microsoft Word, for example. I know that there is already a post about "Save As" button but here is a difference. You click "Save" and if your file has not been saved earlier, you will get a window with possibility to set a name, directory etc. But if you have already saved the file, you will not get that window (unlike with "Save As"), changes will be saved for the file and this is exactly what I need
So I have this event, can somebody help me what's next?
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
}
P.S. Already tried this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\Documents";
saveFileDialog1.Title = "Saving files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "";
saveFileDialog1.Filter = "All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 1;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamWriter file = new System.IO.StreamWriter(saveFileDialog1.FileName.ToString());
file.WriteLine(richTextBox1.Text);
file.Close();
}
}
It seems to me that you'd just need to track whether or not they've already saved the document, by capturing the file path in a variable. This way, if the value is not set you can show the dialog, and if it is set you just use the path to save the content.
You'd also want to update this variable in the SaveAs and Open events if you have them.
Here's an example:
// Stores the name and path of the current file
private string filePath = null;
// Enum to enable us to easily reuse the same method for getting a file path
// while still showing the appropriate dialog title (see 'UpdateFilePath')
private enum DialogType
{
Open,
Save,
SaveAs
}
// Shows a dialog (based on 'dialogType') and captures the path in our variable
private bool UpdateFilePath(DialogType dialogType)
{
FileDialog dialog;
if (dialogType == DialogType.Open)
{
dialog = new OpenFileDialog();
}
else
{
dialog = new SaveFileDialog();
}
dialog.Filter = "All Files (*.*)|*.*";
dialog.Title = dialogType == DialogType.SaveAs
? "Save File As"
: dialogType + " File";
if (dialog.ShowDialog() == DialogResult.OK && dialog.FileName.Length > 0)
{
filePath = dialog.FileName;
return true;
}
return false;
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
var originalPath = filePath;
if (UpdateFilePath(DialogType.Open))
{
try
{
richTextBox1.LoadFile(filePath);
}
catch
{
MessageBox.Show("Unable to load specified file.");
filePath = originalPath;
}
}
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(filePath))
{
if (UpdateFilePath(DialogType.Save))
{
richTextBox1.SaveFile(filePath);
}
}
else
{
richTextBox1.SaveFile(filePath);
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
if (UpdateFilePath(DialogType.SaveAs))
{
richTextBox1.SaveFile(filePath);
}
}

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.

Keep opening OpenFileDialog until selecting valid file

I have code that opens the OpenFileDialog, I'm checking the size of the file to make sure it doesn't exceed specific limit.
But, if the user selected a big sized file I need to warn him and lead him back to the dialog to select a different file or click cancel.
This is what I've tried:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
while (dialog.ShowDialog() != DialogResult.Cancel)
{
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000)
{
MessageBox.Show("File size exceeded");
continue;
}
}
EDIT:
I also tried the following code but it opens the dialog each time the ShowDialog is called. So, if the user selected a file 3x the size the limit, the dialog will appear 3 times.
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
dialog.FileOk += delegate(object s, CancelEventArgs ev)
{
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000)
{
XtraMessageBox.Show("File size");
dialog.ShowDialog();
}
};
if (dialog.ShowDialog() == DialogResult.OK)
{
XtraMessageBox.Show("File Selected");
}
You are half-way there, the FileOk event is what you want to use. What you are missing is setting the e.Cancel property to true. That keeps the dialog opened and avoids you having to display it over and over again. Like this:
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
dialog.FileOk += delegate(object s, CancelEventArgs ev) {
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000) {
MessageBox.Show("Sorry, file is too large");
ev.Cancel = true; // <== here
}
};
if (dialog.ShowDialog() == DialogResult.OK) {
MessageBox.Show(dialog.FileName + " selected");
}
ev.Cancel = true; Check if following piece of code serves your purpose?
public void SomeMethod()
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.FileOk += new CancelEventHandler(dialog_FileOk);
dialog.Filter = "Jpeg files, PDF files, Word files|*.jpg;*.pdf;*.doc;*.docx";
dialog.ShowDialog();
}
void dialog_FileOk(object sender, CancelEventArgs e)
{
OpenFileDialog dialog = sender as OpenFileDialog;
var size = new FileInfo(dialog.FileName).Length;
if (size > 250000)
{
MessageBox.Show("File size exceeded");
e.Cancel = true;
}
}
Yes as far as your requirement is concern, this is OK but in general opening Dialog after showing a prompt for Size is not the best way. Instead a prompt should be displayed, best is to display the validation error on the size from the main window. And it should be User's duty to select the proper file again by opening the File Dialog again according to Usability principles of HCI.
Add a handler to FileDialog.FileOk and let verify the file size inside their.

WPF Save DialogBox (for windows 64)

This is similar to older posts on this site but I keep getting an error message. I want to create a button in C # WPF that opens a dialogbox and saves a text file to be read at a later date. This code works for windows 32, but crashes on windows 64. How can I change this code to get it to work on both systems? I am a beginner at programming.
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog(); //throws error message here
private void savebutton_Click(object sender, RoutedEventArgs e)
{
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain (*.cur)|*.cur";
saveFile.FilterIndex = 2;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
bool? result = saveFile.ShowDialog();
if (result.HasValue && result.Value)
{
clsSaveFile.s_FilePath = saveFile.FileName;
int iDotLoc = clsSaveFile.s_FilePath.LastIndexOf('.');
string strExtTest = clsSaveFile.s_FilePath.Substring(iDotLoc);
if (strExtTest != ".cur")
clsSaveFile.s_FilePath += ".cur";
FileInfo sourceFile = new FileInfo(clsSaveFile.s_FilePath);
clsSaveFile.saveFile();
}
}
You're setting an invalid FilterIndex, that might have something to do with it.
There is no 2nd filter in the filter string as written:
"CCurtain (*.cur)|*.cur"
Try setting the FilterIndex to 1 or adding another filter to the string.
You should try adding a catch around the statement to get a better idea as to what is going on.
try
{
code here
}
catch (Exception ex)
{
ex.message contains the info
}
Also, check for null:
bool? result = saveFile.ShowDialog();
if (result != null && (result.HasValue && result.Value))
{
// code
}
I would create the dialogbox IN the event. And you don't have two different filters.
private void savebutton_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
saveFile.FileName = Class1.stringjobnum;
saveFile.Filter = "CCurtain|*.cur";;
saveFile.FilterIndex = 1;
saveFile.InitialDirectory = "T:\\Tank Baffle Curtain Calculator\\SavedTanks";
saveFile.OverwritePrompt = true;
// Show open file dialog box
Nullable<bool> result = saveFile.ShowDialog();
// Process open file dialog box results
if (result == true)
{
string filename = saveFile.FileName;
// are you sure you need to check the extension.
// if so extension is a a fileinfo property
}

Set SelectedPath as a variable in FolderBrowserDialog

I am trying to set the selected folder in a FolderBrowserDialog control as a variable, so I can use it within another method
The code I have so far is:
private void button18_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//
// The user selected a folder and pressed the OK button.
// We print the number of files found.
//
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
So I could call the selected folder in the control above in a method like this:
Process.Start("test.exe", <Folder Selection Here> );
I started looking at this before I noticed that you had requested the question to be closed. Anyway here's the code should it be useful for someone else.
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
//Choose the default start up folder
string selectedFolder = #"C:\Dev";
//Set that into the dialog
folderBrowserDialog1.SelectedPath = selectedFolder;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
//Grab the folder that was chosen
selectedFolder = folderBrowserDialog1.SelectedPath;
// The user selected a folder and pressed the OK button.
// We print the number of files found.
string[] files = Directory.GetFiles(selectedFolder);
MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
MessageBox.Show(selectedFolder);
}
}

Categories