Reading From TXT File to Separate Text Boxes - c#

I have been out of the coding game for quite some time now and have forgot most of what I knew. I am looking to be able to read individual lines from a txt file and append them to separate textboxes but keep getting stumped and i'm running out of time for my deadline.
I want the code to do something like this:
Read (Line 1) from (User.txt)
Append (Line 1) to (txtFirstName)
Read (Line 2) from (User.txt)
Append (Line 2) to (txtLastName)
If possible i'd like to have the txt file read in as an array so that the individual lines can be used to fill separate textboxes.
Okay, so what I had written was this:
private void btnUser_Click(object sender, EventArgs e)
{
if(lstbUsers.Text == "Jordan Atkinson")
{
TextReader reader = new StreamReader(#"*FILEADDRESS*Jordan.txt");
txtUserFirstName.Text = reader.ReadLine();
string[] lines = System.IO.File.ReadAllLines(#"*FILEADDRESS*Jordan.txt");
foreach (string line in lines)
{
lstvUsers.Items.Add(line);
}
}
}
However, using the reader.ReadLine() only reads the top line and I want to be able to specify what line I want to read from.

If you want to read just a specific line from your file, you can do that this way:
int lineNumber = 10; // the line which you want to read
string line = File.ReadLines(pathToFile).Skip(lineNumber - 1).First();
This code will return the 10th line of your file. If you want to append this string to another, you can simply use the += operator or StringBuilder class.

Related

C#: Read line from file & determine if it contains a substring

I am working on a program for personal use that will automatically sort a grocery list (from file) into a particular order. I want the program to open the file, read each line, and determine if each line contains certain words. For example, a line could contain "chicken breasts," and the program would just recognize that it contained "chicken." The idea is to have the program automatically order my list so that I'm not running back and forth getting items when I go to the store. Currently the external file line must have the exact text "chicken" for the program to recognize it ("chicken breasts" will not be recognized). Here is the section that I believe is giving me trouble:
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
}
Groceries is an array with each element being a line from the file (I think I created it correctly). Below is the entire code:
private void btnImport_Click(object sender, EventArgs e)
{
//Grocery items
string chicken;
//StreamReader variable
StreamReader readFile;
string filePath;
//Counter variable
int index = 0;
//Display open file dialog box
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//Set filepath as a variable
filePath = openFileDialog1.FileName;
// Assign the file as a variable
readFile = File.OpenText(filePath);
//Count lines in file and create array
int lineCount = File.ReadLines(filePath).Count();
string[] groceries = new string[lineCount];
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
index++;
if (groceries.Contains("chicken"))
{
chicken = "Chicken";
//Display items in label
lstItems.Items.Add(chicken);
}
}
//Close file
readFile.Close();
}
}
When the program is run, it will add "Chicken" to the listbox the same number of times as the number of lines in the file, even though only one line actually contains "chicken." My question is: How can I make it pick out the keyword from a longer line of text, and why is it adding the item more than once? Thanks!
Edit
(Sorry I don't know how to attach a file here)
I am currently importing a .txt file with the following data:
chicken
fish
Frosted Flakes cereal
pork tenderloin
ground beef
First, you need to remove the redundant openFileDialog1.ShowDialog();. And access the elements in groceries by index. Then add additional conditions to exclude rows that contain "chicken breasts". Note that index++ is executed after the if statement.
// define a varibale
bool chickenadded = false;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
// remove the redundant ShowDialog
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// code omitted ...
//Read file's contents
while (index < groceries.Length && !readFile.EndOfStream)
{
groceries[index] = readFile.ReadLine();
// check here
if (groceries[index].Contains("chicken") && !chickenadded /*&& !groceries[index].Contains("chicken breasts")*/)
{
chicken = "Chicken";
lstItems.Items.Add(chicken);
// set to true
chickenadded = true;
// another way is not define boolean, just use "break"
break;
}
// reset index here
index++;
}
Disregarding any other problem or what the overall goal of the application is. You forgot to look at the actual line
if (groceries[index].Contains("chicken"))
It's worth a note that you should likely be using File.ReadLines or File.ReadAllLines instead. As it gives you a collection or enumerable to work with

How do I use a StreamReader to input text from one WPF window to another in C#?

My problem is this, I am writing some software in WPF C# and I need to makeit so that the MainWindow will parse the txt file I have made
and store the information in a data
structure, the data should be passed to the
second Window when it is opened.
I have the StreamReader code working fine, it can locate the txt file, but it won't show the information in the listbox on the second window (I apologize if I have screwed up the formatting, very new to the website)
namespace ACW2
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void inventoryButton_Click(object sender, RoutedEventArgs e)
{
InventoryWindow wnd = new InventoryWindow();
wnd.ShowDialog();
string line;
StreamReader file = new StreamReader(#"G:\P1\txt_files\inventory.txt");
List<int> list = new List<int>();
while ((line = file.ReadLine()) != null) ;
{
ListBox.Items.Add.(Line);
list.Add(int.Parse(line));
}
}
you have few problems here:
semicolon on while ((line = file.ReadLine()) != null) ; line which means that next code block (in curly braces) will not be executed in the loop, but after the loop ends.
What is Line (with capital L) which you are adding to ListBox.Items collection? Where is that Line defined and what is it's value?
what is line (lowercase L this time)?
try to fix those errors and we'll see what's next to be done...
What do you want to reach with
ListBox.Items.Add.(Line);
Maybe you mean this:
ListBox.Items.Add.(line);
You also dont need the semicolon at the end of your while statement.
Edit:
Specify your ListBox on the second window with a x:Name = "myListBox" tag.
After you did that you should be able to add an element to the listbox with wnd.myListBox.Items.Add(line);

c# stream reader reading text file into richtextbox inbetween [] tags

I have a text file that i want to read into a richtextbox on my form using a button
Here is the text file:
[1]
Hello this is a text file. I am reading this into a richtextbox.
I want multiple rows into the textbox to display on one button click.
[/1]
Here is my code:
private void button2_Click(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader(#"F:\test.txt"))
{
bool content = false;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("[1]"))
{
content = true;
}
if (content == true)
{
txtContent.AppendText(reader.ReadLine());
}
if (line.Contains("[/1]"))
{
content = false;
break;
//txtContent.AppendText(reader.ReadLine());
}
}
}
}
When i click button2 it only adds the first line
how can i read all the text in between [1] and [/1]
I have looked into the use of XML but my text file will have alot of data in by the end so ive tried to avoid using it.
I would like to then go onto using the same richtextbox to store text inbetween [2] and [/2] on another button click
Thanks for your help
Your logic looks like it may skips lines.
You read a line in from the file and if it contains [1] you set your flag. Then you check if your flag is set and read another line from the file. So this won't include the previously read line. Then you check if that next line contains[/1] and break from your reading loop.
Say you read your first line and its "[1]Hello this is a text file." Your logic will not include "Hello this is a text file" in the RichTextBox, because you've requested the next line to be read. Then you check for your end tag ([/1]), which would result in false. Now we come back to the top of the loop and read the next line ("I am reading this into a richtextbox."). This will fail your first check, and your content flag is still true so now this current line will not be added to the RichTextBox because we did another ReadLine().
Now your question is stated like the beginning tag ([1]) is on a line by itself. If that's true, then just continue your loop after you set the content flag to true.
If you don't want your tags [1] and [/1] to not be in the RichTextBox then Replace them in the line variable and add the line variable to your RichTextBox. Don't read another line to add to your RichTextBox, just use the line you already read in if it meets your condition of being between your tags.
This snippet should handle all (generic formats) of your file, unless your tags appear again within your tags (For example, "[1][1][/1][/1]")
private void button2_Click(object sender, EventArgs e)
{
using (StreamReader reader = new StreamReader (#"F:\test.txt"))
{
bool content = false;
while ((line = reader.ReadLine()) != null)
{
if (line.Contains("[1]"))
{
content = true;
// You only need this continue if this is on a line by itself
continue;
}
if (content == true)
{
// The Replace should remove your tags and add what's left to the RichTextBox
txtContent.AppendText(line.Replace("[1]", "").Replace("[/1]", ""));
}
if(line.Contains("[/1]"))
{
content = false;
break;
}
}
}
}

Insert a 'Return' after the 60th char in every line for a WPF RichTextBox

I am having some trouble with my custom RichTextBox control.
The RichTextBox does not seem to have any concept of a "Lines" collection. But I need to manage the text by line.
Is there a way to get AND update a line of text in a RichTextBox?
The exact scenario I am going for is to look at each line in the RichTextBox and, if the line has more than 60 chars, insert a Environment.NewLine after the 60th char.
Update:
I have found that you can GET a line with this code:
richTextBox.Document.ContentStart.GetLineStartPosition(lineNumber);
But I still have no way to UPDATE a line.
You simple need to iterate over the lines, check the length, if it's longer than 60, add a new line character. Repeat for all the characters in the line, and return the result.
Below is an outline of the code
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
TextPointer line = richTextBox1.CaretPosition.GetLineStartPosition(0);
if (line.GetOffsetToPosition(richTextBox1.CaretPosition) > 60)
{
line.GetPositionAtOffset(60, LogicalDirection.Forward).InsertLineBreak();
}
}
The above code is useful, if you are running the formatting once.
This code adds a new line if the current line is too long. (This only works on the current line, so it would need to be adapted to more lines for pasting.)
private const int lineLimit = 60;
private static void BlockCurrentToNotExceedMaxChars(TextPointer currentLocation)
{
var currentStart = currentLocation.GetLineStartPosition(0);
var nextStart = currentLocation.GetLineStartPosition(1);
var currentEnd = (nextStart != null ? nextStart : currentLocation.DocumentEnd).GetInsertionPosition(LogicalDirection.Backward);
TextRange currentLine = new TextRange(currentStart, currentEnd);
if (currentLine.Text.Trim().Length > lineLimit)
{
currentStart.GetPositionAtOffset(lineLimit + 1).InsertLineBreak();
}
}

What is the fastest way to load text file into RichTextBox?

I load text file into RichTextBox using OpenFIleDialog. But when a large amount of text is (for example song text about 50-70 lines) and I click OPEN program hangs for a few second (~3-5). Is it normal? Maybe there is some faster way or component to load text file? If my question is an inappropriate just delete it. Thanx.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string text = File.ReadAllText(openFileDialog1.FileName);
for (int i = 0; i < text.Length - 1; i++)
{
richTextBox1.Text = text;
}
}
I guess maybe ReadAllLines impeds it?
There is a similar question that deals with the fastest way of reading/writing files: What's the fastest way to read/write to disk in .NET?
However, 50-70 lines is nothing.. no matter how you read, it should fly in immediately. Are you maybe reading from a network share or something else that is causing the delay?
Edit:
Now that I see your code: Remove the loop and just write richTextBox1.Text = text; once. It doesn't make sense to assign the string in the loop since you already read the complete content of the file by using ReadAllText.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
string text = File.ReadAllText(openFileDialog1.FileName);
richTextBox1.Text = text;
}
void LoadFileToRTB(string fileName, RichTextBox rtb)
{
rtb.LoadFile(File.OpenRead(fileName), RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you
// or
rtb.LoadFile(fileName);
// or
rtb.LoadFile(fileName, RichTextBoxStreamType.PlainText); // second parameter you can change to fit for you
}
Remove the for loop, because is useless:
string text = File.ReadAllText(openFileDialog1.FileName);
richTextBox1.Text = text;
text is a string that already contains all the text of the file to pass to the textBox.
Doing:
for(int i=0, i < text.Lengt-1; i++)
richTextBox1.Text = text;
you're assigning the text read from the file text.Length-1 times (Length is the number of characters of the string) and that's useless.
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
richTextBox1.Text = File.ReadAllText(openFileDialog1.FileName);
}

Categories

Resources