Overwriting a text file from RichTextBox - c#

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 ?

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#, saving from menu strip, and save as button

I am trying to save my rich text box content to a a file. However I am getting the error when I am trying to save a new file. Save as works as expected. Any suggestions. Thank you
System.ArgumentException: 'Empty path name is not legal.'
My code for the save and save as button are as follows:
OpenFileDialog file_open = new OpenFileDialog();
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
filename = file_open.FileName;
RichTextBoxStreamType stream_type;
// Checks the extension of the file to save
if (filename.Contains(".txt"))
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
DialogResult retval = saveDlg.ShowDialog();
if (retval == DialogResult.OK)
filename = saveDlg.FileName;
else
return;
RichTextBoxStreamType stream_type;
if (saveDlg.FilterIndex == 2)
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
MessageBox.Show("File Saved");
}

Save stream of savefiledialog in c#

In my wpf app I have an "Export" button that suppose to save some json file to chosen path.
I mean my question is how to write the file, let's say he has the path D:\somefile.json to the chosen location that the user chose from save dualog?
Here my code:
void Export_button_Click(object sender, RoutedEventArgs e)
{
Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Json files (*.json)|*.json";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
This should be something like:
Copy(StreamOf(D:\somefile.json),ChosenPath)
SaveFileDialog sf = new SaveFileDialog();
sf.Filter = "Json files (*.json)|*.json";
sf.FilterIndex = 2;
sf.RestoreDirectory = true;
if (sf.ShowDialog() == DialogResult.OK)
{
System.IO.File.Copy(#"D:\somefile.json", sf.FileName, true);
}
you can use File.copy
public static void Copy(
string sourceFileName,
string destFileName)
for more info you can visit https://msdn.microsoft.com/en-us/library/c6cfw35a(v=vs.110).aspx

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

Doing a file I/O project and cannot seem to get my file to save

When I click on the file drop down where I have new, for new file, I prompt the user. If they have data in the textbox, if they would like to save what they have done before starting a new file. I get the save prompt dialog box to pop up and all that but I wont save the file.
private void mnuFileNew_Click(object sender, EventArgs e)
{
if (txtText.Text.Trim().Length <= 0)
{
lblStatus.ForeColor = Color.BlueViolet;
lblStatus.Text = "New file!";
}
else
{
if (MessageBox.Show("Start new file without saving?", "Exit",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
{
try
{
SaveFileDialog sfd = new SaveFileDialog();
// set properties
sfd.Title = "Where would you like to save this?";
sfd.InitialDirectory = #"c:\Users\public";
sfd.Filter = "Text File (*.txt)|*.txt|All files (*.*)|*.*";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
lblStatus.Text = sfd.FileName;
lblStatus.ForeColor = Color.Navy;
}
// show a message
lblStatus.ForeColor = Color.BlueViolet;
lblStatus.Text = "The Text has been uploaded!";
}
catch (Exception ex)
{
lblStatus.ForeColor = Color.Red;
lblStatus.Text = ex.Message;
}
}
else
{
txtText.Text = "";
}
you need to create the file
if(sfd.ShowDialog() == DialogResult.OK)
{
using(StreamWriter sw = new StreamWriter(sfd.FileName))
{
sw.WriteLine(YourTextBox.Text);
}
}

Categories