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.
Related
In my company it is common to name files in the following manner: 210808_Filename.extension
Unfortunately both of these ways to get the filename failed: Path.GetFileName() and OpenFileDialog.SafeFileName. In the path itself the underscores exist, but in the filename they get removed.
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
string strCheck = "";
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
strConfigPath1 = openFileDialog1.FileName;
if (strConfigPath1.Length > 6)
{
strCheck = strConfigPath1.Substring(strConfigPath1.Length - 6);
}
if (strConfigPath1 == "" || strCheck != ".gcode")
{
MessageBox.Show("Selected file has to be a GCode file.");
}
else
{
lblSelectedDocument.Content = System.IO.Path.GetFileName(string);
}
}
I know it may not be a well programmed code due to the fact I am bloody new to programming. Sorry for that.
Here's a straightforward way to set the contents of the label, based on the file that the user selects:
private void btnOpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
if (openFileDialog.ShowDialog() == true)
{
string chosenFilename = openFileDialog.FileName;
if (Path.GetExtension(chosenFilename).ToLower() == ".gcode")
{
lblSelectedDocument.Content = "Valid file. You selected " + chosenFilename;
}
else
{
lblSelectedDocument.Content = "Invalid file - not a .GCODE file. You selected " + chosenFilename;
}
}
else
{
lblSelectedDocument.Content = "You did not select a file.";
}
}
If the user doesn't select a file, we just set the label to be You did not select a file.
If the user did select a file, we check if the file extension is our intended extension. The check is case-insensitive, so .GCODE, .GcOdE, .gcode (etc) will all work. If the user selected a gcode file, the label says the filename is valid and shows the filename.
If the file extension doesn't match, the user must have selected an invalid file. When this occurs we tell them the filename is invalid and show the filename.
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);
}
}
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;
}
}
I am using C# and a winform and am saving data to a .xlsx on a button click event. I have a unique situation that I am not sure how to code for....
If the form is still displayed and the user clicks the button, I want it to prompt for a file name and save location. BUT if the form has not been closed and the user clicks the button a second time, I want .xlsx to be saved in the same location and with the same filename and over write with no prompt.
This is the syntax I use to prompt for save name and location, but how do I check to determine if a filename/save location has already been input and if it has do not prompt again?
private void btnOne_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { Messagebox.Show("An error has occured"; }
}
}
So, whether the data has a set filename is a part of the state of the class. Inside the class where you have btnOne_Click, just define a string with the filename, defaulted to null:
string filepath = null;
Then, in your btnOne_Click, you want to check for the filepath. If it's not there, open the saveAs dialog. After that, if filepath is set, just save. It will be restructured like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (filepath == null)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK) {
filepath = save.FileName;
}
}
if (filepath != null)
{
try
{
var file = new FileInfo(filepath);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"; }
}
}
This logical structure gives you standard behavior for when a user presses a save button. If they cancel the saveAs dialog, then the save is aborted and the filename state is not changed.
Declare this globally:
public string Filename;
Then change your subroutine like this:
private void btnOne_Click(object sender, EventArgs e)
{
if (string.IsNullOrWhiteSpace(Filename))
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xlsx";
if (save.ShowDialog() == DialogResult.OK)
{
try
{
Filename = save.FileName;
var file = new FileInfo(save.FileName);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
catch { MessageBox.Show("An error has occured"); }
}
}
else
{
var file = new FileInfo(Filename);
using (var package = new ExcelPackage(file))
{
package.Save();
}
}
}
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
}