C#, saving from menu strip, and save as button - c#

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

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

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

Pass File Name and Location From SaveFileDialog To Variable

I have been just hard coding a save name/location, but now I need to ask the user for the save location and file name. I have this syntax, but how do I actually pass the selected location & input file name to my ToExcel() method to know the file name and save locaiton?
private void btnSave_Click(object sender, EventArgs e)
{
//Creating Save File Dialog
SaveFileDialog save = new SaveFileDialog();
//Showing the dialog
save.ShowDialog();
//Setting default directory
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
//Setting title
save.Title = "Select save location and input file name";
//filtering to only show .xml files in the directory
save.DefaultExt = "xml";
//Write Data To Excel
ToExcel();
}
private void ToExcel()
{
var file = new FileInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), "Test_" + DateTime.Now.ToString("M-dd-yyyy-HH.mm.ss") + ".xlsx"));
using (var package = new ExcelPackage(file))
{
ExcelWorksheet ws = package.Workbook.Worksheets.Add("Test");
ws.Cells[1, 1].Value = "One";
ws.Cells["A1:C1"].Style.Font.Bold = true;
package.Save();
MessageBox.Show("Saved!");
}
}
Firstly ShowDialog should be the last line of your call, after you have configured it
then use the FileName Property to access the selected Filename
finally pass that to whatever you need to pass it to ie
private void btnSave_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = #"C:\";
save.RestoreDirectory = true;
save.Title = "Select save location file name";
save.DefaultExt = "xml"; // surely should be xlsx??
//Showing the dialog
if(save.ShowDialog() == DialogResult.OK)
{
ToExcel(save.FileName);
}
}
private void ToExcel(string saveFile){...}
also if you want to get the Directorty of a FileInfo check the FileInfo.Directory property

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 ?

How to read a file after we open OpenFileDialog?

I couldn't find any method to add in the if statement to read a text file. Here is the code;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog BrowseFile1 = new OpenFileDialog();
BrowseFile1.Title = "Select a text file";
BrowseFile1.Filter = "Text File |*.txt";
BrowseFile1.FilterIndex = 1;
string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
BrowseFile1.InitialDirectory = #ContainingFolder;
//BrowseFile1.InitialDirectory = #"C:\";
BrowseFile1.RestoreDirectory = true;
if (BrowseFile1.ShowDialog() == DialogResult.OK)
{
}
I just wanna get whole text froma text file that I choose from this OpenFolderDialog window.
string text = System.IO.File.ReadAllText(BrowseFile1.FileName);
Another possibility is using a StreamReader:
http://msdn.microsoft.com/en-us/library/db5x7c0d(v=vs.110).aspx
Just Change the file locatations through BrowseFile1.FileName.

Categories