Write textbox text to a file while keeping newlines - c#

I have tried using:
StreamWriter.WriteLine()
StreamWriter.Write()
File.WriteAllText()
But all of those methods write the textbox text to the file without keeping newlines and such chars. How can I go about doing this?
EDIT:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(s.FileName, richTextBox1.Text);
}
}
I am using a multiline RichTextBox to do this.

To expand on tzortzik's answer, if you use StreamWriter and simply access the RichTextBox's Lines property, it will do the work for you:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(s.FileName))
{
foreach (string line in richTextBox1.Lines)
{
sw.WriteLine(line);
}
}
}
}

Maybe this would help. Is from StreamWriter class documentation.
string[] str = String.Split(...);
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
The idea is to get the text from your textbox and then split it after \n char. The result will be an array of strings, each element containing one line.
Later edit:
The problem is that return carriage is missing. If you look with debugger at the code, you will see that your string has only \n at a new line instead of \r\n. If you put this line of code in you function, you will get the results you want:
string tbval = richTextBox1.Text;
tbval = tbval.Replace("\n", "\r\n");
There should be other solutions for this issue, looking better than this but this one has quick results.

Related

Read textfile and show it in richtextbox. Show one word from Richtextbox in ComboBox then find it in text and replace it with TextBox.text

I have opened a .CSV file in RichTextBox.I added every line's first word to CombobBox items. I want to edit this a specific word and then save it back to the File.
This is how i open the file to richTextBox1.
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Csv files (.csv)|*.csv";
ofd.Title = "Open a file...";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName);
richTextBox1.Text = sr.ReadToEnd();
}
Now i want a Button that finds my comboBox1.Text in richTextBox and replace it with txtbox.Text.
My button looks like this:
private void button1_Click(object sender, EventArgs e)
{
using (TextReader reader = new StringReader(richTextBox1.Text))
{
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
}
}
I would add the method to the end of this button that would save back the text from richTextBox to my .CSV file but this replace method doesnt replace anything in my richTextBox.
My .CSV file (in richTextBox) looks like this:
somestring,somenumber,somespecialcharacters;
somestring2,somenumber2,somespecialcharacters2;
It has about 50 lines,and my combobox is filled with the first words of every line like: "somestring" "somestring2".
When i click on somestring (then its my combobox.text) then i write "newstring" to my txtbox.text. When i click my button it should find comboBox.text in richtxt and replace it with my txtbox.text.
Any ideas why it doesnt work?
You wrote:
but this replace method doesnt replace anything in my richTextBox.
This is because strings in C# are immutable? Whatever you do to strings, the original string is never changed. The result is always in a new string.
See Why .NET String is immutable?
So although your code changes the value of str, the original str that your richtextbox displays is not changed.
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
str refers to a new string. RichTextBox1.Text still refers to the original string.
Solution: Assign the new string to the rich text box:
this.RichTextBox1.Text = str;
If you want to save the text in a file you'll have to create a FileWriter that will write the new string (not the changed string, strings can't change!).
Depending on how important it is that you don't lose the old file in case of problems, consider using a tmpfile to write, delete the original and move the tmpfile
In order to replace or delete something using a stream reader, you will need to delete every line and replace it with a new (temporary) file.
var tempFile = Path.GetTempFileName(); //Creates temporary file
List<string> linesToKeep = new List<string>(); //Creates list of all the lines you want to keep (everything but your selection)
using (FileStream fs = new FileStream(path(), FileMode.Open, FileAccess.Read)) //(this opens a new filestream (insert your path to your file there)
{
using (StreamReader sr = new StreamReader(fs)) //here is starts reading your file line by line.
{
while (!sr.EndOfStream) //as long it has not finished reading
{
string currentline = sr.ReadLine().ToString(); //this takes the current line it has been reading
string splitline = currentline; //this is a temporary string because you are going to have to split the lines (i think you have 3 so split in "," and then index the first line (your identifier or name)))
if (splitline.Split(';')[0] != ID) //split the line and add your personal identifier so it knows what to keep and what to delete.
{
linesToKeep.Add(currentline); //adds the line to the temporary file list of line that you want to keep
}
}
}
}
File.WriteAllLines(tempFile, linesToKeep); //writes all the lines you want to keep back into a file
File.Delete(path()); //deletes the old file
File.Move(tempFile, path()); //moves temporary file to old location of the old file.
On second notice, check out this code:
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(ofd.FileName);
}
}
I think this is more in line with what you had in mind?

Remove text line in XML file C# .NET

i need to write app to remove specific text line in very large XML file (about 3,5 GB).
I wrote this code:
string directoryPath;
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
ofd.Filter = "XML|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
directoryPath = Path.GetDirectoryName(ofd.FileName);
textBox2.Text = directoryPath;
textBox1.Text = ofd.SafeFileName;
}
}
private void Replace()
{
StreamReader readerFile = new StreamReader(ofd.FileName, System.Text.Encoding.UTF8);
while (!readerFile.EndOfStream)
{
string stringReplaced;
string replaceResult = textBox2.Text + "\\" + "replace_results";
Directory.CreateDirectory(replaceResult);
StreamWriter writerFile = new StreamWriter(replaceResult + "\\" + textBox1.Text, true);
StringBuilder sb = new StringBuilder();
char[] buff = new char[10 * 1024 * 1024];
int xx = readerFile.ReadBlock(buff, 0, buff.Length);
sb.Append(buff);
stringReplaced = sb.ToString();
stringReplaced = stringReplaced.Replace("line to remove", string.Empty);
writerFile.WriteLine(stringReplaced);
writerFile.Close();
writerFile.Dispose();
stringReplaced = null;
sb = null;
}
readerFile.Close();
readerFile.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
toolStripStatusLabel1.Text = "Replacing in progress...";
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Replace();
toolStripStatusLabel1.Text = "Replacing complete!";
}
catch
{
toolStripStatusLabel1.Text = "Error! Replacing aborted!";
}
}
}
it works, but not as well because new file (after remove lines) is bigger than original file and at the end of new file are added some junk (lots of dots), screenshot:
https://images81.fotosik.pl/615/873833aa0e23b36f.jpg
How i can fix my code to make new file the same as old file, only without specific lines?
For a start why keep opening and closing the output file? Keep it open.
Secondly reading blocks – which could lead to "line to remove" being split across blocks – and writing lines is an odd mix.
But I expect your issue is three fold:
You do not set the encoding of the output file.
When you read the buffer (10MB) you may get fewer characters read – the return from ReadBlock. But you always write the complete block. Limit the write to match the amount read (as updated but the replace).
ReadBlock will include end of lines, but WriteLine will add them: either work on blocks or on lines. Mixing will only create problems (and avoid the second issue above).
This leads to code something like:
using (var rdr = OpenReadFile(...))
using (var wtr = OpenWriteFile(...)) {
string line;
while ((line = rdr.ReadLine()) != null) {
line = line.Replace(x, y);
str.WriteLine(line);
}
}
NB Processing XML as text could lead to corrupting the XML (there is no such thing as "invalid XML": either the document is valid XML or it isn't XML, just something that looks a bit like it might be XML). Therefore any such approach needs to be handled with caution. The "proper" answer is to process as XML with the streaming APIs (XmlReader and XmlWriter) to avoid parsing the whole document as one.
I trying do this by XmlTextReader but i have system.xml.xmlexception during read my file, screenshot: https://images82.fotosik.pl/622/d98b35587b0befa4.jpg
Code:
XmlTextReader xmlReader = new XmlTextReader(ofd.FileName);
XmlDocument doc = new XmlDocument();
doc.Load(xmlReader);

How to save content from List<string> to a text file in C#?

I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. When my form closes, the playlist content is saved to a .txt file. When I open again my application, the content in the text file is stored again in the listbox and the playlist. But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones.
This is the code I use to WRITE the content of playlist(List) in the txt file:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(listBox1.Items.Count > 0)
{
StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
foreach (String s in playlist)
{
str.WriteLine(s);
}
str.Close();
}
This is the code used to READ the same txt file:
private void Form1_Load(object sender, EventArgs e) //Form Load!!!
{
FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
if(info.Exists)
{
if (info.Length > 0)
{
System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
try
{
do
{
string currentRead = reader.ReadLine();
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
} while (true);
}
catch (Exception)
{
reader.Close();
listBox1.SelectedIndex = 0;
}
}
else
{
File.Delete(Application.StartupPath + "/Text.txt");
}
}
else
{
return;
}
}
The code used to add files to listbox and playlist:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select File(s)";
ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
ofd.InitialDirectory = "C:/";
ofd.RestoreDirectory = false;
ofd.Multiselect = true;
ofd.ShowDialog();
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
playlist.Add(s);
}
listBox1.SelectedIndex = 0;
This is what I get when I add new files after re-opening my form:
Thanks in advance, I hope StackOverflow community can help me!
First of all: debug your code and you'll find the problem yourself :)
Issue is the use of the WriteLine method. The last line you write should use the Write method instead so that you don't have an empty line at the end. Alternatively and easier to implement is to only add non-empty lines to your playlist such like this:
// ...
do
{
string currentRead = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
{
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
}
} while (true);
As a side comment: while (true) and using exception handling is a bad approach to end a loop.

Getting extra lines, but I don't know why

I am making a WPF program, and right now I want to be able to open and merge files. I have a button to open a file and I have a button to merge the file, and when I don't implement the "onTextChanged" method both buttons work properly and the files are formatted properly. But if I implement the onTextChanged method and use the merge file button, the previous 'file' gets extra lines in its output.
Open Button Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
Merge Button Code:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
And when I execute this code, it adds lines in between the last 'file's output:
private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
If you are wondering why I don't use the Split method of a string, it is because I need to open 50+ MB text files and I get an out of memory exception upon using it. I really just want to keep formatting the same when I merge a file.
Wow this is a one line fix.
Original Line of Code:
buffer.Add(sb.ToString());
Changed (Correct) Line of Code:
buffer.Add(sb.ToString().Trim());
The changed worked, however if someone has any idea where these extra lines are coming from that would be helpful.

How to save text font (which was set up manually) with a text in C#

I set up the font manually for the labels, however, when I am saving it as a Word Document the font which I set up previously disappears. I do not know how to figure it out
private void button1_Click(object sender, EventArgs e)
{
string text = label1.Text + textBox1.Text + "\r\n\r\n\r\n" +
label2.Text + textBox2.Text + "\r\n\r\n\r\n";
sSaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Microsoft Word| *.doc";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
MessageBox.Show(path);
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(text);
}
}
}
}
StreamWriter (basically) writes a string (of characters) to a file. Word formatting is not that simple. If you want the formatting then it gets more complicated.
See this MSDN article for more info on formatting Word documents. You need an object that can control the document.

Categories