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

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);
}
}

Related

Only ask for filename if one has not been input

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();
}
}
}

Overwriting a text file from RichTextBox

Now if you write the text and click on the save button, OpenFileDialog will appear. If you finish something in the same document and click on the save button again, you need to select the save location again. How to make that when saving the same file you do not need to create a new file each time, and just overwrite the current one? Sorry for my English.
private void buttonSave_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
}
else
{
}
}
It sure is, you just need to remember the last file path you saved and not display the dialog again the next time around; something like this should help:
void Main()
{
Save();
}
private string _filePath = "";
void Save()
{
var overwrite = false;
if (!string.IsNullOrEmpty(_filePath))
{
var res =
MessageBox.Show("Would you like to overwrite your last saved file?", "Overwrite?", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1,
MessageBoxOptions.DefaultDesktopOnly, false);
if (res == DialogResult.Cancel) return;
if (res == DialogResult.No) overwrite = false;
if (res == DialogResult.Yes) overwrite = true;
}
if (!overwrite)
{
var sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File|*.rtf";
var res = sfd.ShowDialog();
if (res != DialogResult.OK) return;
_filePath = sfd.FileName;
}
// do the richTextBox.SaveFile(_filePath) here.
}
In this example it:
CHECK IF FILE PATH ALREADY SET
IF NOT THEN
ASK USER IF THEY WANT TO OVERWRITE THE LAST FILE
IF CANCEL THEN DON'T SAVE
IF YES THEN SET OVERWRITE TO TRUE
IF NO THEN SET OVERWRITE TO FALSE
END IF
CHECK IF OVERWRITING
IF OVERWRITING THEN
SHOW SAVE FILE DIALOG
IF USER DIDN'T CLICK OK THEN DON'T SAVE
IF USER CLICKED OK, SET THE NEW FILE PATH TO USE
END IF
SAVE THE FILE USING THE NOW-REMEMBERED FILE PATH
Perhaps:
private void SaveButton_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = #"C:\";
saveFileDialog1.Title = "Save text Files";
saveFileDialog1.CheckFileExists = true;
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.DefaultExt = "txt";
saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = saveFileDialog1.FileName;
}
}
Example from: http://www.c-sharpcorner.com/uploadfile/mahesh/savefiledialog-in-C-Sharp/
Might help some?
private string filePath = string.Empty;
private void SaveButton_Click(object sender, EventArgs e)
{
if (File.Exists(filePath))
{
byte[] buffer = Encoding.ASCII.GetBytes(richTextBox1.Text);
MemoryStream ms = new MemoryStream(buffer);
//write to file
FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
}
else
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Rich Text File | *.rtf";
sfd.OverwritePrompt = false;
if (sfd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(sfd.FileName);
filePath = sfd.FileName;
}
}
}
you can use sfd.OverwritePrompt = false; property to avoid prompt messagebox if file already exists, is this what you are looking for ?

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 do i read already opened file in a another button click event directly .(i.e without open file dialogue in button click)

void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
var geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
}
How to read files in button1 click directly?
what you want is that your geometry object be accessible in additional scopes besides OpenPolyFile(). So you can simply make the geometry declaration accessible to both methods, declaring it, say, in the form code behind
// class scoped variables
[ThePolyFileType] (pick the right one here :) geometry = null;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
}
}
void OpenPolyFile(string file)
{
geometry = TriangleNet.IO.FileReader.ReadPolyFile(file);
// ...
}
private void button1_Click(object sender, EventArgs e)
{
if (geometry != null)
{
//do your stuff
}
}
How do i read already opened file in a another button click event
directly .(i.e without open file dialogue in button click)
I'm not quite sure why you want to read it twice, but if that requirement says, make selected filename available globally and use it.
private string filename;
void OpenWithDialog()
{
var ofd = new OpenFileDialog();
ofd.Filter = "Triangle polygon file|*.poly";
if (ofd.ShowDialog() == DialogResult.OK)
{
OpenPolyFile(ofd.FileName);
filename = ofd.FileName
}
}
Now you have opened filename available in button_clcik you can use this file and read again.
private void button1_Click(object sender, EventArgs e)
{
// now you can read the file.
//File.ReadAllText(filename); //OR
TriangleNet.IO.FileReader.ReadPolyFile(file);
}

Choose file C# and get directory

I'm trying to open a file dialog box so the user can choose the location of an access database. Can someone explain how to add a file dialog when a button is clicked and also how to transform the user choice into a string that contains the file directory ( c:\abc\dfg\1234.txt)?
Thanks
As you did not state the technology you use (WPF or WinForms), I assume you use WinForms. In that case, use an OpenFileDialog in your code. After the dialog was closed, you can get the selected full file name using the FileName property.
There is the following example of how to use it on the documentation page I linked above, which I modified slightly as you want the file name, not the stream:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "Database files (*.mdb, *.accdb)|*.mdb;*.accdb" ;
openFileDialog1.FilterIndex = 0;
openFileDialog1.RestoreDirectory = true ;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
string selectedFileName = openFileDialog1.FileName;
//...
}
}
Based on your previous question I assume you are using WinForms.
You can use the OpenFileDialog Class for this purpose. See the code below which will run on your button Click event assuming your button id is button1:
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "Access files (*.accdb)|*.accdb|Old Access files (*.mdb)|*.mdb";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
var path = openFileDialog1.FileName;
}
}
More information.
Assuming that you actually have a form with button (button1)...
At the constructor hook into button1's click event
...
button1.Click += button1_Click;
...
Then define the handling function and use System.Windows.Forms.OpenFileDialog as you like.
void button1_Click(object sender, EventArgs e)
{
string oSelectedFile = "";
System.Windows.Forms.OpenFileDialog oDlg = new System.Windows.Forms.OpenFileDialog();
if (System.Windows.Forms.DialogResult.OK == oDlg.ShowDialog())
{
oSelectedFile = oDlg.FileName;
// Do whatever you want with oSelectedFile
}
}
It's actually fairly simple
namespace YourProgram
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path = "";
//Declare the File Dialog
OpenFileDialog ofd = new OpenFileDialog();
private void button1_click(object sender, EventArgs e)
{
if (odf.ShowDialog() == DialogResult.OK)
{
path = ofd.FileName;
}
}
}
}

Categories