RichTextBox to Text File Wont Save LineBreaks - c#

I have a RichTextBox and a Button that saves its text to a .txt file.
However it does not save the LineBreaks \n. It ends up all in one line.
What could be preventing it? I'm using Encoding.Unicode.
XAML
<RichTextBox x:Name="rtbMessage" Margin="10,10,10,50" />
<Button x:Name="btnSave" Content="Save" Margin="231,264,211,29" Width="75" Click="btnSave_Click"/>
C#
String message = "Hello, world.\n\n This is a test.";
Paragraph p = new Paragraph();
// Startup
// Write Message to RichTextBox
//
public MainWindow()
{
InitializeComponent();
rtbMessage.Document = new FlowDocument(p);
rtbMessage.BeginChange();
p.Inlines.Add(new Run(message));
rtbMessage.EndChange();
}
// Copy RichTextBox to String
//
public String MessageRichTextBox()
{
FlowDocument fd = new FlowDocument(p);
rtbMessage.Document = fd;
TextRange textRange = new TextRange(
rtbMessage.Document.ContentStart,
rtbMessage.Document.ContentEnd
);
return textRange.Text;
}
// Save Message to .txt File
//
private void buttonSave_Click(object sender, RoutedEventArgs e)
{
Microsoft.Win32.SaveFileDialog saveFile = new Microsoft.Win32.SaveFileDialog();
// Save File Default Path same as Input Directory
saveFile.RestoreDirectory = true;
saveFile.Filter = "Text file (*.txt)|*.txt";
saveFile.DefaultExt = ".txt";
saveFile.FileName = "Message";
// Show Save File dialog box
Nullable<bool> result = saveFile.ShowDialog();
// Process dialog box
if (result == true)
{
// Save document
File.WriteAllText(saveFile.FileName, MessageRichTextBox(), Encoding.Unicode);
}
}

Looks like you are resetting the message when you grab it
public String MessageRichTextBox()
{
FlowDocument fd = new FlowDocument(p);
rtbMessage.Document = fd;
Seems unnecessary and might the cause. I cant validate without a windows machine next to me (sorry on a Mac right now), just give it a try though

I use richtextbox, but I use Environment.NewLine instead of "\n".
In your example:
String message = "Hello, world." + Environment.NewLine + Environment.NewLine + "This is a test.";
Maybe that is a workaround.

Change
TextRange textRange = new TextRange(
rtbMessage.Document.ContentStart,
rtbMessage.Document.ContentEnd);
To
TextRange textRange = new TextRange(
p.ContentStart,
p.ContentEnd)

Related

Stream reader cannot get the text from file text to a textbox

try
{
Form frmShow = new Form();
TextBox txtShowAll = new TextBox();
frmShow.StartPosition = FormStartPosition.CenterScreen;
frmShow.Font = this.Font;
frmShow.Size = this.Size;
frmShow.Icon = this.Icon;
frmShow.Text = "All data";
txtShowAll.Dock = DockStyle.Fill;
txtShowAll.Multiline = true;
frmShow.Controls.Add(txtShowAll);
frmShow.ShowDialog();
StreamReader r = new StreamReader("empData.txt");
string strShowAllData = r.ReadToEnd();
txtShowAll.Text = strShowAllData;
r.Close();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
I sure that is the file name is correct
when I run the program it shows an empty text box.
The result
I just noticed you are adding text to the textbox after showing the form in dialog mode. Why don't you move the frmShow.ShowDialog(); to the end of the try block just like I have done it in the code below, and make sure the empData.txt exists at its path.
try
{
Form frmShow = new Form();
TextBox txtShowAll = new TextBox();
frmShow.StartPosition = FormStartPosition.CenterScreen;
frmShow.Font = this.Font;
frmShow.Size = this.Size;
frmShow.Icon = this.Icon;
frmShow.Text = "All data";
txtShowAll.Dock = DockStyle.Fill;
txtShowAll.Multiline = true;
frmShow.Controls.Add(txtShowAll);
StreamReader r = new StreamReader("empData.txt");
string strShowAllData = r.ReadToEnd();
txtShowAll.Text = strShowAllData;
r.Close();
frmShow.ShowDialog();
}
catch (Exception x)
{
MessageBox.Show(x.Message);
}
As noted other places, the actual problem stems from the show dialog blocking before you can execute your dialog
There are a couple of things here
Why don't you create a dedicated Form i.e MyDeciatedShowAllForm, instead of dynamically creating it
If you are using something that implements IDisposable, Its best to use a using statement
Example
using(var r = new StreamReader("empData.txt"))
{
string strShowAllData = r.ReadToEnd();
txtShowAll.Text = strShowAllData;
}
Why don't you use File.ReadAllText instead, save your self some printable characters
Example
string strShowAllData = File.ReadAllText(path);
You probably need to set the TextBox to MultiLine
Example
// Set the Multiline property to true.
textBox1.Multiline = true;
// Add vertical scroll bars to the TextBox control.
textBox1.ScrollBars = ScrollBars.Vertical;
// Allow the RETURN key to be entered in the TextBox control.
textBox1.AcceptsReturn = true;
// Allow the TAB key to be entered in the TextBox control.
textBox1.AcceptsTab = true;
// Set WordWrap to true to allow text to wrap to the next line.
textBox1.WordWrap = true;
// Show all data
textBox1.Text = strShowAllData;
Why don't you check if the file exists first using File.Exists
Exmaple
if(!File.Exists("someFile.txt"))
{
MessageBox.Show(!"oh nos!!!!! the file doesn't exist");
return;
}
Lastly, and this is one you need to remember, you need to learn how to use the debugger and breakpoints, Navigating through Code with the Debugger. I mean, you should have known if there is text or not in your text file if you had just put a breakpoint on txtShowAll.Text = strShowAllData; there should be no doubt in your mind or ours.

C# Visual Studio - I'm trying to read a text file and display it into Richtextbox and include new lines

I'm trying to read a text file and display it into Richtextbox and include new lines.
Say I want it to read as:
Hello
Hello
Hello
But it is reading as:
HelloHelloHello
This is the code that I have so far:
private void btnView_Click(object sender, EventArgs e)
{
OpenFileDialog op = new OpenFileDialog();
op.InitialDirectory = "C:\\";
op.Filter = "Txt files (*.txt)|*.txt|All Files (*.*)|*.*";
op.FilterIndex = 2;
if (op.ShowDialog() == DialogResult.OK)
{
textBox1.Text = op.FileName;
string path = op.FileName;
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while(sr.Peek() >= 0)
{
sb.Append(sr.ReadLine());
Console.WriteLine("\r\n");
}
}
richTextBox1.Text = sb.ToString();
}
}
StreamReader lines are delimited by Environment.NewLine. If you'd read the documentation you would have noticed ReadLine does not include these delimiters. If you want to re-add them use:
sb.Append(sr.ReadLine());
sb.Append(Environment.NewLine);
And don't call Console.WriteLine() in a WinForms app.
Another way you can do it is to use the File class's static ReadAllText() method.
You just pass it the path to a text file, and it will read all the text (line breaks included) into a string and return it to you. Then you can just set the result of that to your richTextBox1.Text property for some much cleaner and easier to read code:
if (op.ShowDialog() == DialogResult.OK)
{
textBox1.Text = op.FileName;
richTextBox1.Text = File.ReadAllText(op.FileName);
}
change the line:
Console.WriteLine("\r\n");
to:
sb.Append("/r/n");

Exporting a .txt, no overwrite warning appears

When executing the following code, I would expect a warning pop up dialog, which will ask if I am sure I would like to overwrite the file, but no pop up appears. Does anyone know a simple way to implement it? Without having to create my own custom window
XAML:
<Grid>
<TextBox x:Name="name" Text="hi" />
<Button x:Name="create_File" Click="create_File_Click" Content="make the notepad" Width="auto"/>
</Grid>
c#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
public void createFile()
{
string text_line = string.Empty;
string exportfile_name = "C:\\" + name.Text + ".txt";
System.IO.StreamWriter objExport;
objExport = new System.IO.StreamWriter(exportfile_name);
string[] TestLines = new string[2];
TestLines[0] = "****TEST*****";
TestLines[1] = "successful";
for (int i = 0; i < 2; i++)
{
text_line = text_line + TestLines[i] + "\r\n";
objExport.WriteLine(TestLines[i]);
}
objExport.Close();
MessageBox.Show("Wrote File");
}
private void create_File_Click(object sender, RoutedEventArgs e)
{
createFile();
}
}
UPDATE
I was not using SaveFileDialog, Now I am and it works just how I would expect it too... thanks for the answers, here is what I have now:
public void createFile()
{
string text_line = string.Empty;
string export_filename = name.Text;
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = export_filename; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// save file
System.IO.StreamWriter objExport;
objExport = new System.IO.StreamWriter(dlg.FileName);
string[] TestLines = new string[2];
TestLines[0] = "****TEST*****";
TestLines[1] = "successful";
for (int i = 0; i < 2; i++)
{
text_line = text_line + TestLines[i] + "\r\n";
objExport.WriteLine(TestLines[i]);
}
objExport.Close();
}
private void create_File_Click(object sender, RoutedEventArgs e)
{
createFile();
}
}
Asking the user whether the file should be overwritten is usually done when the file path is chosen, not when the file is actually written.
If you let the user choose the path using a SaveFileDialog, the OverwritePrompt property is set to true by default, resulting in the confirmation dialog you desire.
If you don't want to use the SaveFileDialog, you can use a MessageBox with the MessageBoxButtons.YesNo option.
1) Check if the File exists (File.Exists)
2) If it does, display a MessageBox (MessageBox.Show) with yes and no options.
3) Check if the user clicked yes, and only then execute the rest of your code
DialogResult dialogResult = File.Exists(exportfile_name)
? MessageBox.Show(null, "Sure?", "Some Title", MessageBoxButtons.YesNo)
: DialogResult.Yes;
if (dialogResult == DialogResult.Yes)
{
// save file
}

SaveFileDialog saves as blank ext? - C#

So I got the hang of doing OpenFileDialog, now I can't seem to understand SaveFileDialog. Looked at a few pages and each of them have there own ways of doing it, but none of them get down to the point of saving the text that is in the richtextbox to a file.
private void button1_Click(object sender, EventArgs e)
{
Stream myStream;
SaveFileDialog exportdialogue = new SaveFileDialog();
exportdialogue.Filter = "txt files (*.txt)|*.txt*";
exportdialogue.FilterIndex = 2;
exportdialogue.RestoreDirectory = true;
if (exportdialogue.ShowDialog() == DialogResult.OK)
{
if ((myStream = exportdialogue.OpenFile()) != null)
{
StreamWriter wText = new StreamWriter(myStream);
wText.Write("Some Text");
myStream.Close();
}
}
}
Using a richtextbox, and a normal button, also "using System.IO;" (For the Stream )
I am trying to get the button to use SaveFileDialog so it can export the content within the richtextbox to a text file.
Issue:
Unsure what I need to do from here to make it save contents from the rich text box.
Don't know why SaveFileDialog saves files with no extension when a filter is in place.
You set:
exportdialogue.Filter = "txt files (*.txt)|*.txt*";
which only contains ONE filter, but you set:
exportdialogue.FilterIndex = 2;
which means to use the SECOND filter. (FilterIndex is 1-based).
If you set FilterIndex = 1, your file should have the extension .txt
you can use using {} block to solve the issue:
Try this:
SaveFileDialog exportdialogue = new SaveFileDialog();
exportdialogue.Filter = "txt files (*.txt)|*.txt*";
exportdialogue.FilterIndex = 2;
exportdialogue.RestoreDirectory = true;
if (exportdialogue.ShowDialog() == DialogResult.OK)
{
using( Stream myStream = exportdialogue.OpenFile())
{
StreamWriter wText = new StreamWriter(myStream);
wText.Write("Some Text");
wText.Close();
}
}
you need to use savefile method of reach textbox and pass to it the filename from savedialogbox.
reachtextbox.SaveFile(exportdialogue.FileName);
ps: it will be something like above code.

How do I show the name of the current open file in the Form title?

I'm making a text editor and I'd like to display the name of the current open file in the Form title (like Notepad does where it says "Untitled - Notepad" or " "File - Notepad").
I'm assuming this is done working with the SaveFileDialog and OpenFileDialog, so I'll post my current code.
OpenFile:
private void OpenFile()
{
NewFile();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (ofd.ShowDialog() != DialogResult.OK) return;
StreamReader sr = null;
try
{
sr = new StreamReader(ofd.FileName);
this.Text = string.Format("{0} - Basic Word Processor", ofd.FileName);
richTextBoxPrintCtrl1.Text = ofd.FileName;
richTextBoxPrintCtrl1.Text = sr.ReadToEnd();
filepath = ofd.FileName;
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch
{
}
finally
{
if (sr != null) sr.Close();
}
SaveFile
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
filepath = sfdSaveFile.FileName;
SaveFile();
this.Text = string.Format("{0} - Basic Word Processor", sfdSaveFile.FileName);
}
catch (Exception exc)
{
}
void SetWindowTitle(string fileName) {
this.Text = string.Format("{0} - Basic Text Editor", System.IO.Path.GetFileNameWithoutExtension(OpenFileDialog.Filename));
How can I get the file name and put it in the Form's title (like Notepad does where it has the name of the file followed by the name of the text editor).
While opening . . .
private void OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
ofd.ShowDialog();
try
{
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(ofd.Filename));
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader stread = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = stread.ReadToEnd();
stread.Close();
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
catch { }
}
While saving . . .
private void SaveFileAs()
{
SaveFileDialog sfdSaveFile = new SaveFileDialog();
sfdSaveFile.Title = "Save File";
sfdSaveFile.FileName = "Untitled";
sfdSaveFile.Filter = "Rich Text Files (*.rtf)|*.rtf|Text Document (*.txt)|*.txt|Microsoft Word Document (*.doc)|*.doc|Hypertext Markup Language Document (*.html)|*.html";
if (sfdSaveFile.ShowDialog() == DialogResult.OK)
try
{
richTextBoxPrintCtrl1.SaveFile(sfdSaveFile.FileName, RichTextBoxStreamType.RichText);
filepath = sfdSaveFile.FileName;
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(sfd.Filename));
}
catch (Exception exc)
{
}
}
Just an update
Toby- The empty catch blocks are needed. If the user cancels the ofd or sfd without the catch block, the program crashes. It keeps the program from crashing
You do not need the catch block to check if User selected OK / Cancel.
OpenFileDialog & SaveFileDialog has method ShowDialog that returns DialogResult
and value of DialogResult.OK tells that user has selected file to open / save and has not cancelled the operation.
And example with OpenFile
private void OpenFile()
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open File";
ofd.FileName = "";
ofd.Filter = "Rich Text Files (.rtf)|.rtf|Text Document (.txt)|.txt|Microsoft Word Document (.doc)|.doc|Hypertext Markup Language Document (.html)|.html";
if (ofd.ShowDialog() == DialogResult.OK)
{
// just one line is added
this.Text = string.Format("{0} - MyNotepad", Path.GetFileName(ofd.Filename));
richTextBoxPrintCtrl1.Text = ofd.FileName;
StreamReader stread = new StreamReader(richTextBoxPrintCtrl1.Text);
richTextBoxPrintCtrl1.Text = stread.ReadToEnd();
stread.Close();
richTextBoxPrintCtrl1.LoadFile(fileName, RichTextBoxStreamType.RichText);
}
}
You can wrap it in a function like this:
void SetWindowTitle(string fileName) {
this.Text = string.Format("{0} - MyEditor", System.IO.Path.GetFileName(fileName));
}
..and pass in the dialog FileName..
EDIT:
Your issue is that you're not calling the function I gave you. You have the function I gave you above.. but you don't call it.
Replace this:
this.Text = string.Format("{0} - Basic Word Processor", sfdSaveFile.FileName);
With this:
SetWindowTitle(sfdSaveFile.FileName);
And replace this:
this.Text = string.Format("{0} - Basic Word Processor", ofd.FileName);
With this:
SetWindowTitle(ofd.FileName);

Categories

Resources