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

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).

Related

How to save selected text from richTextBox to file

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

c# , Winform application -search for specific line and replace it with other line

I have a small winform app with a button, which, when clicked, I want to search a text file (file.txt) for a specific word and replace the entire line on which it was found by something else.
Let's say my text file is:
ohad yes no
box cat dog
etc...
I want to search for ohad and once find it replace the line "ohad yes no" to new line "yes I did it"
so the txt file will be:
yes I did it
box cat dog
etc...
This is my code so far:
string lineX;
StringBuilder sb = new StringBuilder();
using (System.IO.StreamReader file = new System.IO.StreamReader(textBox20.Text))
{
while ((lineX = file.ReadLine()) != null)
{
if (lineX.Contains("SRV"))
{
sb.AppendLine(lineX.ToString());
}
}
}
StreamReader streamReader;
streamReader = File.OpenText(textBox20.Text);
string contents = streamReader.ReadToEnd();
streamReader.Close();
StreamWriter streamWriter = File.CreateText(textBox20.Text);
streamWriter.Write(contents.Replace(sb.ToString(), textBox26.Text + textBox29.Text + textBox30.Text + textBox27.Text + textBox28.Text));
streamWriter.Close();
Thanks you all in advance
Ohad
Try this:
// Read file into a string array (NOTE: You should check if exists first!)
string[] Lines = File.ReadAllLines(textBox20.Text);
for(int i=0;i<Lines.Length;i++) {
if(Lines[i].Contains("SRV")) {
Lines[i] = "New value for line";
// if you only want to replace one line, uncomment the next row:
// break;
}
}
// Write array back to file
File.WriteAllLines(textBox20.Text, Lines);
for a starter, how about following these comments i put together.
var s = #"
ohad yes no
box cat dog
";
//split string into array
//go through each item in array
//check if it contains "ohad"
//if so, replace that line with my text
//convert array to string

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

C# - Comparing/Replacing Text Using Two .txt Files

I want to take in a certain format of one text file. After the first file is loaded and reformatted, I want to open a second text file and check if the second file has any text matches with the first re-formatted file. Right now I am successfully reformatting the first text file to how I want it. The first (reformatted) text file looks like this:
1 0010 12345 DEF, DEF-0320
1 0020 ABC-00010G ABC-A,1xx,10%,x1x,0603
1 0020A ABC-00010G ABC-A,1xx,10%,x1x,0603
1 0030A ABC-00127G ABC,4.7xx,10%,x1x,0805
.
.
.
I want to know how to take this file (above) and find the second column (0010, 0020, 0020A, 0030A, ...) and compare it/search for it in a second text file. The format for the second text file will look something like this:
10 BARE PCB
20 T C40, C3112
B D5, D45, D48
30 B R25
.
.
.
Once I am able to find the match from the first file (0010, 0020, 0020A, 0030A) with the second file (10, 20, B, 30) I want to grab the lines after the 10, 20, B, 30 and replace the first files 0010, 0020, 0020A, 0030A with them. Also, if the number from the first one does not end with an "A" (ie, 0010) I want to put a "T" at the end of the new file. However, if it does end with an "A" (ie, 0030A) I want to put a "B" at the end of the file. Also, for every value in the second file that is in the format "C40" (or similar) I want to place on a new line if there is multiple (seperated by a ",") and copy the same information from the above line. This meaning it would look like this:
1 AAAA BCD 12345 DEF, DEF-0320 T
1 C40 ABC-00010G ABC-A,1xx,10%,x1x,0603 T
1 C3112 ABC-00010G ABC-A,1xx,10%,x1x,0603 T
1 D5 ABC-00010G ABC-A,1xx,20%,x1x,0603 B
1 D45 ABC-00010G ABC-A,1xx,20%,x1x,0603 B
1 D48 ABC-00010G ABC-A,1xx,20%,x1x,0603 B
1 R25 ABC-00127G ABC,4.7xx,100%,x1x,0805 B
General basis of my code:
Open button: Opens a txt file.
Save button: Saves the new formatted text file where ever I want to save it to.
Clear button: Clears the text in all of the rich text boxes I use.
OpenRefs button: Opens the second txt file used to compare with the first file.**
**I am also trying to get this button to output the final formatting of the text into the final rich text box.
Here is my current code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Text.RegularExpressions;
namespace Formatter
{
public partial class Form : Form
{
// Create a OpenFileDialog to request a path and file name to open.
OpenFileDialog openFile = new OpenFileDialog();
OpenFileDialog openRefs = new OpenFileDialog();
public Form()
{
InitializeComponent();
}
private void openButton_Click(object sender, EventArgs e)
{
// Initialize the OpenFileDialog to specify the .txt extension as well as
// its intial directory for the file.
openFile.DefaultExt = "*.txt";
openFile.Filter = ".txt Files|*.txt";
openFile.InitialDirectory = "C:\\";
openFile.RestoreDirectory = true;
try
{
// Open the contents of the file into the originalTextRichTextBox.
if (openFile.ShowDialog() == DialogResult.OK && openFile.FileName.Length > 0)
originalTextRichTextBox.LoadFile(openFile.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
// Resets the formattedTextRichTextBox so multiple files aren't loaded on top of eachother.
formattedTextRichTextBox.ResetText();
foreach (string line in File.ReadAllLines(openFile.FileName))
{
// Uses regular expressions to find a line that has, digit(s), space(s), digit(s) + letter(s),
// space(s), digit(s), space(s), any character (up to 25 times).
Match theMatch = Regex.Match(line, #"^[\.*\d]+\s+[\d\w]+\s+[\d\-\w*]+\s+.{25}");
if (theMatch.Success)
{
// Stores the matched value in string output.
string output = theMatch.Value;
// Sets the formattedTextRichTextBox to the string output.
formattedTextRichTextBox.AppendText(output);
formattedTextRichTextBox.AppendText("\n");
}
}
}
// Catches an exception if the file was not opened.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void saveButton_Click(object sender, EventArgs e)
{
// Create a SaveFileDialog to request a path and file name to save.
SaveFileDialog saveFile = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the .txt extension for the file.
saveFile.DefaultExt = "*.txt";
saveFile.Filter = ".txt Files|*.txt";
saveFile.InitialDirectory = "C:\\";
saveFile.RestoreDirectory = true;
try
{
// Save the contents of the formattedTextRichTextBox into the file.
if (saveFile.ShowDialog() == DialogResult.OK && saveFile.FileName.Length > 0)
formattedTextRichTextBox.SaveFile(saveFile.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
}
// Catches an exception if the file was not saved.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void clearButton_Click(object sender, EventArgs e)
{
try
{
// Resets the text in all of the boxes.
originalTextRichTextBox.ResetText();
formattedTextRichTextBox.ResetText();
refsTextRichTextBox.ResetText();
finalTextRichTextBox.ResetText();
}
// Catches an exception if the either text box could not be cleared.
catch (Exception)
{
MessageBox.Show("Could not clear the text.", "Clearing Text Box Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void openRefsButton_Click(object sender, EventArgs e)
{
// Initialize the OpenFileDialog to specify the .txt extension as well as
// its intial directory for the file.
openRefs.DefaultExt = "*.txt";
openRefs.Filter = ".txt Files|*.txt";
openRefs.InitialDirectory = "C:\\";
openRefs.RestoreDirectory = true;
try
{
// Open the contents of the file into the originalTextRichTextBox.
if (openRefs.ShowDialog() == DialogResult.OK && openRefs.FileName.Length > 0)
refsTextRichTextBox.LoadFile(openRefs.FileName, RichTextBoxStreamType.PlainText);
// Throws a FileNotFoundException otherwise.
else
throw new FileNotFoundException();
// ********************************************
// ********************************************
// ********************************************
// FROM HERE DOWN IS WHERE I NEED THE HELP! :)
// ********************************************
// ********************************************
// ********************************************
string[] refLines = System.IO.File.ReadAllLines(openRefs.FileName);
foreach (string line in refLines)
{
finalTextRichTextBox.AppendText(line + "\n");
}
try
{
using (StreamReader readRefs = new StreamReader(openRefs.FileName))
{
originalTextRichTextBox.ResetText();
List<string> refFileLines = new List<string>();
while (!readRefs.EndOfStream)
{
refFileLines.Add(readRefs.ReadLine());
}
using (StreamReader readFile = new StreamReader(openFile.FileName))
{
List<string> fileLines = new List<string>();
while (!readFile.EndOfStream)
{
fileLines.Add(readFile.ReadLine());
}
}
refFileLines.Contains("");
}
}
catch (Exception)
{
MessageBox.Show("Could not read file.", "Read File Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
// Catches an exception if the file was not opened.
catch (Exception)
{
MessageBox.Show("There was not a specified file path.", "Path Not Found Error", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
}
}
I am getting a little lost on what to do. I was trying to take in each line and store it in a list of strings and once I had both files (open button and openrefs button) read into two sets of List I was going to use string.contains("some_string") but in the files the numbers could each time I open a different file. I am not sure how I would go about iterating properly though each item in each list to compare the strings (that can be different each 'session'). I was also going to concatinate them together and add the final result into another List and write it to the final rich text box. However, I am getting lost and am pretty new to C#. Any help would be greatly appreciated.
Question: How can I compare these two text files, put them into a list properly, compare the two lists for values that are similar, replace the values in the first file with the following text from the matched values in the second file? If this is confusing, let me know!
Thanks in advance! :)
If your columns are delimited with spaces, or some other character(s), using string.Split to make an array of columns. Pick out the column you want and store it in a SortedList (column is both key and value), checking each time you add to ensure no duplicates are added. Read your second file one line at a time, foreach on SortedList keys, and if string.Contains the key, flag the line as having one of the column values.
I don't really get the formatting of your records because you say you are splitting with a space but your records won't split correctly on that. If your file is a fixed length file then you can use .substring to pull data out. If I am reading your question right I think you are going to want to read each line of the first file and add it the line into a hashset using the second column as a key and then the rest of the line as the value. Then cycle through the second file and for each value in the line find the key it goes with and print the value from the key along with the value of the line you just read. You can then find a spot to add a condition that if the key has an "A" or what not you also print a "T" at the end. I think you should stay away from the regex because performance is generally lacking and I don't think it's what you need here.
string strFileName = DisplayFile("Please Select File 1", ".txt", null);
StreamReader srInput = File.OpenText(strFileName);
Hashtable newHash = new Hashtable();
while(srInput.Peek > -1)
{
string temp = srInput.ReadLine();
string parts = temp.Split('//put delimiter here');
newHash.Add(parts[1]//your key should be your second column value,parts [2]//this is your value);
}
//then read in your second file and test each line to see if it has a match in the first file.
string strFileName2 = DisplayFile("Please Select File 2", ".txt", null);
StreamReader srInput2 = File.OpenText(strFileName);
while(srInput2.Peek > -1)
{
string temp2 = srInput.Readline();
string[] parts2 = temp2.Split('delim');
if(newHash.ContainsKey(parts[whichever is the column you want to check is]))
{
//then print to value to new file or list
//newList.Add(parts[that were checked] + newHash[parts that were checked]);
}
}
something like that will work.

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