How to save selected text from richTextBox to file - c#

I'm selecting text in richTextBox1 and I can't save it to .txt file.
I was trying in many ways but only output I get was:
all text from file
output: true
Code that I'm using right now:
SaveFileDialog saveFiles = new SaveFileDialog();
saveFiles.DefaultExt = "*.txt";
saveFiles.Filter = "txt Files | *.txt";
if (saveFiles.ShowDialog() == DialogResult.OK)
{
StreamWriter sw = File.CreateText(saveFiles.FileName);
foreach (String s in richTextBox1.Lines)
{
sw.WriteLine(s);
}
sw.Flush();
sw.Close();

You only want to save the selected text, but your code is trying to save all the text. Try it this way:
File.WriteAllText(saveFiles.FileName, richTextBox1.SelectedRtf);
If you are interested in only the selected text part of the box, you can try something like this:
File.WriteAllLines(saveFiles.FileName,
richTextBox1.SelectedText.Split(new[] { "\n" }, StringSplitOptions.None));

Here is another method for saving the entire RichTextBox content as RTF
richTextBox.SelectAll();
using (var f=File.OpenWrite(filepath)) {
richTextBox.Selection.Save(f, DataFormats.Rtf);
}

Related

How can i write multiple lines in a textfile to different textboxes?

What i did to write from the boxes to the txt file
private void save2_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Textdokument|*.txt";
sfd.FilterIndex = 1;
sfd.RestoreDirectory = true;
if (sfd.ShowDialog() == DialogResult.OK)
{
if ((myStream = sfd.OpenFile()) != null)
{
StreamWriter sw = new StreamWriter(myStream);
sw.WriteLine(TextBoxCardname1.Text);
sw.WriteLine(TextBoxCardname2.Text);
sw.WriteLine(TextBoxCardname3.Text);
sw.WriteLine(TextBoxCardname4.Text);
sw.WriteLine(TextBoxCardname5.Text);
sw.WriteLine(TextBoxCardname6.Text);
sw.WriteLine(TextBoxCardname7.Text);
sw.WriteLine(TextBoxCardname8.Text);
sw.WriteLine(TextBoxCardname9.Text);
sw.WriteLine(TextBoxCardname10.Text);
sw.WriteLine(TextBoxCardname11.Text);
sw.WriteLine(TextBoxCardname12.Text);
sw.WriteLine(TextBoxCardname13.Text);
sw.WriteLine(TextBoxCardname14.Text);
sw.WriteLine(TextBoxCardname15.Text);
sw.WriteLine(TextBoxCardname16.Text);
sw.WriteLine(TextBoxCardname17.Text);
sw.WriteLine(TextBoxCardname18.Text);
sw.WriteLine(TextBoxCardname19.Text);
sw.WriteLine(TextBoxCardname20.Text);
sw.WriteLine(TextBoxCardname21.Text);
sw.WriteLine(TextBoxCardname22.Text);
sw.WriteLine(TextBoxCardname23.Text);
sw.WriteLine(TextBoxCardname24.Text);
sw.WriteLine(TextBoxCardname25.Text);
sw.WriteLine(TextBoxCardname26.Text);
sw.WriteLine(TextBoxCardname27.Text);
sw.WriteLine(TextBoxCardname28.Text);
sw.WriteLine(TextBoxCardname29.Text);
sw.WriteLine(TextBoxCardname30.Text);
sw.Close();
myStream.Close();
}
}
}
Assuming what you meant by your question is that you want to take the contents of each line of a textfile and write it to its corresponding textbox.text; this should work for you:
TextBoxCardname1.Text = System.IO.File.ReadLines("Your Text File").Skip(0).Take(1).First();
TextBoxCardname2.Text = System.IO.File.ReadLines("Your Text File").Skip(1).Take(1).First();
TextBoxCardname3.Text = System.IO.File.ReadLines("Your Text File").Skip(2).Take(1).First();
//...etc
For each line you're reading, you specify how many lines you want to skip, and how many lines you want to read (ie. Skip(1), Take (1) means you would skip the first line in the text file, and read the second line).
If you're trying to get the textbox.text and write it to your textfile (it's kind of hard to tell from your question) This is a simple, yet messy, and labor-intensive method:
var lines = System.IO.File.ReadAllLines("Your text file");
lines[0] = TextBoxCardname1.text);
System.IO.File.WriteAllLines("Your text file", lines);
var lines = System.IO.File.ReadAllLines("Your text file");
lines[1] = TextBoxCardname2.text);
System.IO.File.WriteAllLines("Your text file", lines);
var lines = System.IO.File.ReadAllLines("Your text file");
lines[2] = TextBoxCardname3.text);
System.IO.File.WriteAllLines("Your text file", lines);
//...etc
This method is a very simple way to write to a certain line in a text file. lines[3] would denote the 4th line in the text file, since the line numbering starts at zero [0] (The first line in the text file).

Creating and saving files in C#

I need to create and write to a .dat file. I'm guessing that this is pretty much the same process as writing to a .txt file, but just using a different extension.
In plain english I would like to know how to:
-Create a .dat file
-Write to it
-And save the file using SaveFileDialog
There are a few pages that I've been looking at, but I think that my best explanation will come from this site because it allows me to state exactly what I need to learn.
The following code is what I have at the moment. Basically it opens a SaveFileDialog window with a blank File: section. Mapping to a folder and pressing save does not save anything because there is no file being used. Please help me use this to save files to different locations.
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "";
dlg.DefaultExt = "";
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
string filename = dlg.FileName;
}
Pages that I've been looking at:
-http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
-http://social.msdn.microsoft.com/Forums/en-US/cd0b129f-adf1-4c4f-9096-f0662772c821/how-to-use-savefiledialog-for-save-text-file
-http://msdn.microsoft.com/en-us/library/system.io.file.createtext(v=vs.110).aspx
Note that the SaveFileDialog only yields a filename but does not actually save anything.
var sfd = new SaveFileDialog {
Filter = "Text Files (*.txt)|*.txt|All files (*.*)|*.*",
// Set other options depending on your needs ...
};
if (sfd.ShowDialog() == true) { // Returns a bool?, therefore the == to convert it into bool.
string filename = sfd.FileName;
// Save the file ...
}
Use the filename you are getting from the SaveFileDialog and do the following:
File.WriteAllText(filename, contents);
That's all if you intend to write text to the file.
You can also use:
File.WriteAllLines(filename, contentsAsStringArray);
using(StreamWriter writer = new StreamWriter(filename , true))
{
writer.WriteLine("whatever your text is");
}

How to export the contents of the string or textbox to txt file that remains the same format (If string has 5 lines, txt file will has 5 lines)?

if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileInfo Myfile = new FileInfo(saveFileDialog1.FileName);
StreamWriter wri = Myfile.CreateText();
wri.WriteLine(Richtextbox.Text);
wri.Close();
}
When I export to a text file, all the lines in richtextbox stick into one line. I donnot know how to keep file txt'content same as in richtextbox'content.
You can use SaveFile method
Richtextbox.SaveFile(FileName, RichTextBoxStreamType.PlainText);
foreach (var line in Richtextbox.Lines)
{
wri.WriteLine(line);
}

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

Save text from rich text box with 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.

Categories

Resources