Save text from rich text box with C# - c#

This question has been answered. I've improved the code a bit (at least I think so). It now reminds of the aceepted answer to the question Open file in rich text box with C#. If I haven't made any mistakes (which I may have), the code should save a file with text from the rich text box rtfMain. The default file extension is .txt. You can also use the file extension .rtf.
private void menuFileSave_Click(object sender, EventArgs e)
{
// Create a new SaveFileDialog object
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
// Default file extension
dlgSave.DefaultExt = "txt";
// SaveFileDialog title
dlgSave.Title = "Save File As";
// Available file extensions
dlgSave.Filter = "Text Files (*.txt)|*.txt|RTF Files (*.rtf)|*.rtf";
// Show SaveFileDialog box and save file
if (dlgSave.ShowDialog() == DialogResult.OK)
{
// Save as .txt file
if (Path.GetExtension(dlgSave.FileName) == ".txt")
{
rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
}
// Save as .rtf file
if (Path.GetExtension(dlgSave.FileName) == ".rtf")
{
rtfMain.SaveFile(dlgSave.FileName, RichTextBoxStreamType.PlainText);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
}
private void rtfMain_TextChanged(object sender, EventArgs e)
{
}
Update: I have improved the code even further (at least I think so). The main difference is that you now have more control over the file encoding. This is the code I'm using right now:
private void fileSave_Click(object sender, EventArgs e)
{
// Text from the rich textbox rtfMain
string str = rtfMain.Text;
// Create a new SaveFileDialog object
using (SaveFileDialog dlgSave = new SaveFileDialog())
try
{
// Available file extensions
dlgSave.Filter = "All Files (*.*)|*.*";
// SaveFileDialog title
dlgSave.Title = "Save";
// Show SaveFileDialog
if (dlgSave.ShowDialog() == DialogResult.OK && dlgSave.FileName.Length > 0)
{
// Save file as utf8 without byte order mark (BOM)
// ref: http://msdn.microsoft.com/en-us/library/s064f8w2.aspx
UTF8Encoding utf8 = new UTF8Encoding();
StreamWriter sw = new StreamWriter(dlgSave.FileName, false, utf8);
sw.Write(str);
sw.Close();
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}

Like this:
rtfMain.SaveFile(dlgSave.FileName);

Your code here saves .doc files formatted. When I use it to save .docx files it does save it but when I try to open the saved file using Microsoft Word, An error message is displayed.

Related

button click which makes attachment dialog open

hey guys I am trying to send an attachment file but the attachment dialog is not opening
but instead it is rather telling me 'input string was not in a correct formart
private void proto_Type_AI_Blackhead_God(object sender, RoutedEventArgs e)
{
try
{
OpenFileDialog attachment = new OpenFileDialog();
attachment.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
attachment.Filter = "xml File (*.jpg;*.bmp;*.gif)|*.jpg;*.bmp;*.gif;|Pdf files|*.pdf;|Xml files|*.xml";
if (attachment.ShowDialog() == DialogResult.Value)
{
filename = attachment.FileName;
filename = attachment.SafeFileName;
}
else
{
MessageBox.Show("seriously bad");
}
attachment = null;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
I'm surprised that you got this code compiled.
First of all, OpenFileDialog.ShowDialog() returns bool?, so have it properly checked (for HasValue initally and then the value of Value).
Then, why do you overwrite filename variable? I assume filename is some global variable here.
Further, having that fixed I had no problems running the code, filter string is perfectly correct semantically. Logically, jpegs, bmps and gifs are not XML files.

Unable to automatically save a file after reading it in. c#

I am attempting to create a note taking application (first Windows Forms application). So far I have managed to read a .txt file into a RichTextBox. I am trying to make the program create and save the .txt file containing the contents of the .txt file that was read in read in. So when the user adds text from a file it creates a new file in a notes folders that is in the root directory of application. Please see my code below. Any advice would be greatly appreciated. Cheers
private void button1_Click(object sender, EventArgs e)
{
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = op.FileName;
//create new .txt file contaning module notes
System.IO.StreamWriter file = new System.IO.StreamWriter("\\"+fileName);
file.WriteLine(fileName);
file.Close();
}
Tested and working
//read in a .txt file
OpenFileDialog op = new OpenFileDialog();
if (op.ShowDialog() == DialogResult.OK)
richTextBox1.LoadFile(op.FileName, RichTextBoxStreamType.PlainText);
this.Text = op.FileName;
string fileName = Path.Combine(Application.CommonAppDataPath, Path.GetFileName(op.FileName));
File.WriteAllText(fileName, "test");
wrap your streams, files (anything that implements IDisposable) in a using block:
using(var myfile = File. CreateText(path) ) {
myfile.WriteLine("hi");
}
it's not creating a file because the path is wrong

Save rich text boxes as pdf files and send an email with attachments

I want to save rich text boxes as pdf files. Each time I save a file Adobe Reader can't open it.
private void button3_Click(object sender, EventArgs e)
{
SaveFileDialog MyFiles = new SaveFileDialog();
MyFiles.Filter = "PDF Files|*.pdf";
MyFiles.Title = "Save As...";
MyFiles.DefaultExt = "*.pdf";
if (MyFiles.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(MyFiles.FileName, RichTextBoxStreamType.PlainText);
richTextBox3.SaveFile(MyFiles.FileName, RichTextBoxStreamType.PlainText);
richTextBox4.SaveFile(MyFiles.FileName, RichTextBoxStreamType.PlainText);
richTextBox5.SaveFile(MyFiles.FileName, RichTextBoxStreamType.PlainText);
}
}
I also made send button to send an email with attachments but the problem is I'm unable to send the email:
MailMessage MyMail = new MailMessage(richTextBox1.Text, richTextBox4.Text);
MyMail.To.Add(new MailAddress(richTextBox4.Text));
MailAddress mail = new MailAddress(richTextBox1.Text);
MyMail.From = mail;
MyMail.Subject = richTextBox5.Text;
MyMail.Body = richTextBox3.Text;
MyMail.Attachments.Add(new Attachment(richTextBox2.Text));
SmtpClient MySmtp = new SmtpClient(TheServer.Text);
MySmtp.UseDefaultCredentials = true;
MySmtp.EnableSsl = true;
MySmtp.Port = Convert.ToInt32(ThePort.Text);
MySmtp.Send(MyMail);
May be Save PDF and MS Word File in C# can help you!!!! It uses iTextSharp
Using this or this library can help you. As #JleruOHeP stated in a comment simply renaming the file won't work.
The problem is that, using the method, you cannot save the content of a RichTextBox in the PDF format.
Here you can find the currently available stream format types the can be used: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextboxstreamtype.aspx.
As you see, the main supported type is RTF (Rich Text Format), a plain-text multi-platform format: this is very different from PDF. Look here and here.
EDIT: I just answer to the questioneer's comment asking for some helping code:
// This method opens a dialog and save the content of the passed RichTextBox
private bool ShowRichTextBoxSaveDialog(RichTextBox richTextBox)
{
SaveFileDialog newFileDialog = new SaveFileDialog();
newFileDialog.Filter = "PDF Files|*.pdf";
newFileDialog.Title = "Save As...";
newFileDialog.Filter = "*.pdf";
// If the user confirm the dialog window...
if (newFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
richTextBox.SaveFile(newFileDialog.FileName, RichTextBoxStreamType.PlainText);
// Success!
return true;
}
catch(Exception e)
{
// Error during saving!
MessageBox.Show(String.Concat("Error during saving: ", e.Message));
return false;
}
}
else
// Aborted by the user!
return false;
}
private void button3_Click(object sender, EventArgs e)
{
// NEXT WILL SHOW UP 4 DIALOGS, FOR ASKING THE USER 4 FILES TO SAVE!
this.ShowRichTextBoxSaveDialog(richTextBox1);
this.ShowRichTextBoxSaveDialog(richTextBox3);
this.ShowRichTextBoxSaveDialog(richTextBox4);
// HERE I ALSO CHECK IF THE SAVING IS SUCCESSFUL..
if (this.ShowRichTextBoxSaveDialog(richTextBox5))
MessageBox.Show("Success in saving :)");
else
MessageBox.Show("Failure in saving :(");
}
As everyone has said, you can't simply save RTF and change the extension to make a PDF, they are incompatible formats. Among the many commercial components available, AbcPdf allows you to read in RTF, and then save the output as a PDF: http://www.websupergoo.com/abcpdf-11.htm#note

Text file doesn't get saved but no errors (C#)

I've been looking on many websites now for the answer, but all working answers only work for the richTextbox, and I'm using the normal textbox. I'm trying to save the contents of the textbox to a file of choice, but for some reason the file doesn't get saved, and I have no idea what the problem is. This is the code of the 'save' menu item:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog ofd = new SaveFileDialog();
ofd.Title = "Save";
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
try
{
//I don't know what to make of this, because clearly this doesn't work
File.WriteAllText(#"./TestFile.txt", MainTextbox.Text);
}
catch (Exception ex)
{
MainTextbox.Text += ex;
}
}
}
There is no error.
You should be saving to the file selected in your SaveFileDialog, as retrieved by OpenFile(). This example worked for me:
SaveFileDialog ofd = new SaveFileDialog();
ofd.Title = "Save";
ofd.Filter = "Txt Documents (.txt)|*.txt|All files (*.*)|*.*";
if (ofd.ShowDialog() == DialogResult.OK)
{
using (var fileStream = ofd.OpenFile())
using (var sw = new StreamWriter(fileStream))
sw.WriteLine("Some text");
}
In your code, you let the user select a file to save to, then ignore that and write it to a hardcoded location. It's possible your app didn't have permissions to do this, but it should have permissions to write to a location the user selected.
First off, saving the file has nothing to do with where the text is coming from, rich text box or normal text box.
As Brian S. said in a comment, it is likely there is an exception because you're writing to the C drive. You should use a relative path: "./MyTest.txt"
I think its access denied issue.. try with 'D' drive ...
This is working example.. .WriteAllText works when file already exists and if file already exists then use AppendAllText
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
Use a try { } catch (Exception ex) { } block How to: Use the Try/Catch Block to Catch Exceptions

C# The process can't access the file because it is being used by another process (File Dialog)

I have a rich text box that is being updated with log information. There is a button to save the log output to a file. When I use the code below to try to save the output to a file, I receive "The process can't access the file because it is being used by another process" exception. I am not sure why I am receiving this exception. It happens on new files that I create in the dialog. It happens on any file I try to save the information to.
private void saveLog_Click(object sender, EventArgs e)
{
OnFileDialogOpen(this, new EventArgs());
// Displays a SaveFileDialog so the user can save the Image
// assigned to Button2.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Text File|*.txt|Log File|*.log";
saveFileDialog1.Title = "Save Log File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if (saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch (saveFileDialog1.FilterIndex)
{
case 1:
try
{
this.logWindow.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
break;
case 2:
try
{
this.logWindow.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.PlainText);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
break;
}
fs.Close();
OnFileDialogClose(this, new EventArgs());
}
}
It seems the same file is opened twice. First you create it using:
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
Then you pass the same file name to this.logWindow.SaveFile, which presumably opens the file with the given name and saves data to it.
I guess the first call is unnecessary.

Categories

Resources