Why is streamreader only picking up first entry? c# - c#

I am using the stream reader feature to search for a record in a text file then display that record on the console window. It is searching the text file by a question number (1-50). The only number it works with is question 1. It won't display any other question but it displays question 1 perfect. Here is a section of the code where the problem lies.
static void Amending(QuestionStruct[] _Updating)
{
string NumberSearch;
bool CustomerNumberMatch = false;
Console.Clear();
begin:
try
{
Console.Write("\t\tPlease enter the question number you want to append: ");
NumberSearch = Console.ReadLine();
Console.ReadKey();
}
catch
{
Console.WriteLine("Failed. Please try again.");
goto begin;
}
//finding the question number to replace
while (!CustomerNumberMatch)
{
var pathToCust = #"..\..\..\Files\questions.txt";
using (StreamReader sr = new StreamReader(pathToCust, true))
{
RecCount = 0;
questions[RecCount].QuestionNum = sr.ReadLine();
if (questions[RecCount].QuestionNum == NumberSearch)
{
Console.Clear();
Console.WriteLine("Question Number: {0}", questions[RecCount].QuestionNum);
questions[RecCount].Level = sr.ReadLine();
Console.WriteLine("Level: {0}", questions[RecCount].Level);
questions[RecCount].Question = sr.ReadLine();
Console.WriteLine("Question: {0}", questions[RecCount].Question);
questions[RecCount].answer = sr.ReadLine();
Console.WriteLine("Answer: {0}", questions[RecCount].answer);
CustomerNumberMatch = true;
}
RecCount++;
//sr.Dispose();
}
}

You are reopening the questions.txt file each time around your while loop, so it will start from the beginning of the file each time and never get past the first line (unless you are looking for question 1, when it will read the question detail lines). Instead, you need to loop inside of the using statement:
var pathToCust = #"..\..\..\Files\questions.txt";
using (StreamReader sr = new StreamReader(pathToCust, true))
{
while (!CustomerNumberMatch)
{
RecCount = 0;
questions[RecCount].QuestionNum = sr.ReadLine();
if (questions[RecCount].QuestionNum == NumberSearch)
{
Console.Clear();
Console.WriteLine("Question Number: {0}", questions[RecCount].QuestionNum);
questions[RecCount].Level = sr.ReadLine();
Console.WriteLine("Level: {0}", questions[RecCount].Level);
questions[RecCount].Question = sr.ReadLine();
Console.WriteLine("Question: {0}", questions[RecCount].Question);
questions[RecCount].answer = sr.ReadLine();
Console.WriteLine("Answer: {0}", questions[RecCount].answer);
CustomerNumberMatch = true;
}
RecCount++;
}
}
Something still seems a little off with the code - e.g. you are only populating the question properties when you find a match with NumberSearch, but hopefully this gets you closer.

Related

Program that reads file and writes new info

So basically i have this text data file that contains Basketball player names and heights, i.e. "Tom is 6 ft" . From this text file with the basketball players names and heights I am trying to write a code that runs through each line of the text data file and separate the numbers from the strings, and find that if a player is greater than 6 ft then that player has made it to the team and send that player to another text file called made it. Know that the outcome has been explained I am having trouble trying to create code to be able separate the number from the string and recognise that a player if a player is 6 ft or over and put that player into a new text data file.
Here is the text data file containing the names and heights needed for the program: https://drive.google.com/file/d/10qLuyOzrV2EhFsQ9g4-28rLGIlLFGoDt/view?usp=sharing
Right now I have managed to create a program that reads the text data file and writes another text data file while also displaying line by line all the information in the text file on the console.
This is the code I have right now:
using System;
namespace basketball
{
class Program
{
static void Main(string[] args)
{
// This section shows how to read a file called Sample.txt stored in the Debug folder of the program folder
string fileName = #"Sample.TXT";
Console.WriteLine("The contents of the file {0} is:", fileName);
string[] dataFromFile = new string[100];
int index = 0;
System.IO.StreamReader streamReader = new System.IO.StreamReader(fileName);
using (streamReader)
{
string fileContents = streamReader.ReadToEnd();
dataFromFile[index] = fileContents;
Console.WriteLine(dataFromFile[index]);
index++;
}
Console.WriteLine("Now Line By Line:");
System.IO.StreamReader reader = new System.IO.StreamReader(fileName);
using (reader)
{
int lineNumber = 0;
string line = reader.ReadLine();
while (line != null)
{
lineNumber++;
Console.WriteLine("Line {0}: {1}", lineNumber, line);
line = reader.ReadLine();
}
}
// This section shows how to write a file called madeit.txt stored in the console programs debug folder
string fileName2 = #"madeit.txt";
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(fileName2);
using (streamWriter)
{
for (int number = 1; number <= 20; number++)
{
streamWriter.WriteLine("This is line number : " + number);
}
}
Console.WriteLine("File is written!");
}
}
}
This is currently what the console output looks like, here is a link: https://drive.google.com/file/d/13_WKzfVriXlnfRcaqaPWbNFkc4Xix5z2/view?usp=sharing
I recommend using a regular expression. Please see this example:
List<string> players = new List<string> {
#"Grady is 6'1"" ft",
#"Robert is 5'10"" ft",
#"Riley is 7 ft",
#"Sam is 4'9"" ft",
#"Greg is 6 ft",
#"Raheem is 6'3"" ft",
#"Connor is 5'11"" ft"
};
const string pattern = #"(.+) is (\d+)('\d+"")? ft";
var regex = new Regex(pattern);
foreach (var player in players)
{
var match = regex.Match(player);
if (match.Success)
{
bool sixFeetOrTaller = false;
var name = match.Groups[1].Value;
var inchesStr = match.Groups[2].Value;
int inches;
if (int.TryParse(inchesStr, out inches))
{
if (inches >= 6)
{
sixFeetOrTaller = true;
}
}
if (sixFeetOrTaller)
{
Console.WriteLine(name + " made it to the team!");
}
else
{
Console.WriteLine(name + " did not make it to the team");
}
}
else
{
Console.WriteLine("Unable to parse line " + player);
}
}
Output:
Grady made it to the team!
Robert did not make it to the team
Riley made it to the team!
Sam did not make it to the team
Greg made it to the team!
Raheem made it to the team!
Connor did not make it to the team

Reading every single line from txt file C#

i want to read every single line form txt file. Instead of every line i get every second line. The question is why and how can i do something about it.
list.txt:
60001
60002
60003
60004
..every number in single line and so on 100 lines
StreamReader podz = new StreamReader(#"D:\list.txt");
string pd="";
int count=0;
while ((pd = podz.ReadLine()) != null)
{
Console.WriteLine("\n number: {0}", podz.ReadLine());
count++;
}
Console.WriteLine("\n c {0}", count);
Console.ReadLine();
Because you're reading two lines per loop iteration:
while ((pd = podz.ReadLine()) != null) // here
{
Console.WriteLine("\n number: {0}", podz.ReadLine()); // and here
count++;
}
Instead, just read the line in the first place and use the pd variable in which you store the line in the second place:
while ((pd = podz.ReadLine()) != null)
{
Console.WriteLine("\n number: {0}", pd);
count++;
}
I suggest using File instead of Streams and Readers:
var lines = File
.ReadLines(#"D:\list.txt");
int count = 0;
foreach (var line in lines) {
Console.WriteLine("\n number: {0}", line);
count++;
}
Console.WriteLine("\n c {0}", count);
Console.ReadLine();
Your code has some problems:
You are reading the line incorrectly (calling ReadLine twice per each iteration)
You are not closing the Stream
If the file is in use by another process (i.e. a process writing to the file) you may get some errors
The StreamReader class is useful when the size of the file is very large, and in case you are dealing with a small file you can simply call System.IO.File.ReadAllLines("FileName").
In case the size of the file is large, follow this approach
public static List<String> ReadAllLines(String fileName)
{
using(System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read))
{
using(System.IO.StreamReader sr = new System.IO.StreamReader(fs))
{
List<String> lines = new List<String>();
while (!sr.EndOfStream)
{
lines.Add(sr.ReadLine());
}
return lines;
}
}

Reading doubles from a .txt file and copying them to a new .txt file (Streamreader/Streamwriter)

static void Main(string[] args)
{
Console.Write("Enter the name of the file to open: ");
string input = Console.ReadLine();
Console.Write("Enter the name of the output file: ");
string output = Console.ReadLine();
var InFile = new StreamReader(input);
int TotalD = 0;
StreamWriter OutFile = new StreamWriter(output);
Console.WriteLine();
try
{
using (InFile)
{
double DInput = 0;
while (DInput == double.Parse(InFile.ReadLine()))
{
while (!InFile.EndOfStream)
{
DInput = double.Parse(InFile.ReadLine());
double DOutput = DInput * 2;
InFile.Close();
using (OutFile)
{
OutFile.WriteLine(DOutput);
}
}
InFile.Close();
}
}
using (StreamReader r = new StreamReader(input))
{
TotalD = 0;
while (r.ReadLine() != null) { TotalD++; }
}
}
catch (IOException Except)
{
Console.WriteLine(Except.Message);
}
Console.WriteLine("There were {0} doubles copied to {1}.", TotalD, output);
Console.WriteLine();
Console.Write("Press <enter> to exit the program: ");
Console.Read();
}
Ok so I've asked this question before but the problem was that I didn't know the input.txt file had to be manually written instead of generated like I was doing before. This current version also runs without error messages. The only issue now is that output.txt is completely blank. Any help would be much appreciated!
The idea of this project is to read the doubles from input.txt:
1.5
2.3
3
4.7
5
And write them to output.txt only times 2:
3.0
4.6
6
9.4
10
string input = #"C:\temp\testinput.txt";
string output = #"C:\temp\testoutput.txt";
using (var reader = new StreamReader(input))
{
using (var writer = new StreamWriter(output))
{
var line = reader.ReadLine();
while (line != null)
{
var value = float.Parse(line);
var result = value * 2;
writer.WriteLine(result);
line = reader.ReadLine();
}
}
}
Format the output to the file so it looks like what you want.

Searching for a Specific Word in a Text File and Displaying the line its on

I am having trouble attempting to find words in a text file in C#.
I want to find the word that is input into the console then display the entire line that the word was found on in the console.
In my text file I have:
Stephen Haren,December,9,4055551235
Laura Clausing,January,23,4054447788
William Connor,December,13,123456789
Kara Marie,October,23,1593574862
Audrey Carrit,January,16,1684527548
Sebastian Baker,October,23,9184569876
So if I input "December" I want it to display "Stephen Haren,December,9,4055551235" and "William Connor,December,13,123456789" .
I thought about using substrings but I figured there had to be a simpler way.
My Code After Given Answer:
using System;
using System.IO;
class ReadFriendRecords
{
public static void Main()
{
//the path of the file
FileStream inFile = new FileStream(#"H:\C#\Chapter.14\FriendInfo.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(inFile);
string record;
string input;
Console.Write("Enter Friend's Birth Month >> ");
input = Console.ReadLine();
try
{
//the program reads the record and displays it on the screen
record = reader.ReadLine();
while (record != null)
{
if (record.Contains(input))
{
Console.WriteLine(record);
}
record = reader.ReadLine();
}
}
finally
{
//after the record is done being read, the progam closes
reader.Close();
inFile.Close();
}
Console.ReadLine();
}
}
Iterate through all the lines (StreamReader, File.ReadAllLines, etc.) and check if
line.Contains("December") (replace "December" with the user input).
Edit:
I would go with the StreamReader in case you have large files. And use the IndexOf-Example from #Matias Cicero instead of contains for case insensitive.
Console.Write("Keyword: ");
var keyword = Console.ReadLine() ?? "";
using (var sr = new StreamReader("")) {
while (!sr.EndOfStream) {
var line = sr.ReadLine();
if (String.IsNullOrEmpty(line)) continue;
if (line.IndexOf(keyword, StringComparison.CurrentCultureIgnoreCase) >= 0) {
Console.WriteLine(line);
}
}
}
As mantioned by #Rinecamo, try this code:
string toSearch = Console.ReadLine().Trim();
In this codeline, you'll be able to read user input and store it in a line, then iterate for each line:
foreach (string line in System.IO.File.ReadAllLines(FILEPATH))
{
if(line.Contains(toSearch))
Console.WriteLine(line);
}
Replace FILEPATH with the absolute or relative path, e.g. ".\file2Read.txt".
How about something like this:
//We read all the lines from the file
IEnumerable<string> lines = File.ReadAllLines("your_file.txt");
//We read the input from the user
Console.Write("Enter the word to search: ");
string input = Console.ReadLine().Trim();
//We identify the matches. If the input is empty, then we return no matches at all
IEnumerable<string> matches = !String.IsNullOrEmpty(input)
? lines.Where(line => line.IndexOf(input, StringComparison.OrdinalIgnoreCase) >= 0)
: Enumerable.Empty<string>();
//If there are matches, we output them. If there are not, we show an informative message
Console.WriteLine(matches.Any()
? String.Format("Matches:\n> {0}", String.Join("\n> ", matches))
: "There were no matches");
This approach is simple and easy to read, it uses LINQ and String.IndexOf instead of String.Contains so we can do a case insensitive search.
For finding text in a file you can use this algorithim use this code in
static void Main(string[] args)
{
}
try this one
StreamReader oReader;
if (File.Exists(#"C:\TextFile.txt"))
{
Console.WriteLine("Enter a word to search");
string cSearforSomething = Console.ReadLine().Trim();
oReader = new StreamReader(#"C:\TextFile.txt");
string cColl = oReader.ReadToEnd();
string cCriteria = #"\b"+cSearforSomething+#"\b";
System.Text.RegularExpressions.Regex oRegex = new
System.Text.RegularExpressions.Regex(cCriteria,RegexOptions.IgnoreCase);
int count = oRegex.Matches(cColl).Count;
Console.WriteLine(count.ToString());
}
Console.ReadLine();

c# function inside while won't cycle

hi everybody i have this code
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line = reader.ReadLine();
string app = "";
int i = 0;
while (line != null)
{
i++;
line = reader.ReadLine();
if (line != null)
{
int lunghezza = line.Length;
}
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
the fact is that i have a txt file which i want to translate with this function traduci(targetLanguage,line), the function is ok, i want to translate each line into another file, while is looping the function is blocking at the first loop, if i insert consonle.read() when i press enter the function works...ho can i do? thank you all!
Your code is pretty messy. I would suggest the following method to loop over the StreamReader lines:
using (StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt"))
{
string line;
while (!reader.EndOfStream)
{
line = reader.ReadLine();
// ... process the line
}
}
If ReadLine returns a null, your code will break. better structure:
StreamReader reader = new StreamReader("C:\\Users\\lorenzov\\Desktop\\gi_pulito_neg.txt");
string line;
string app = "";
int i = 0;
while ((line = reader.ReadLine()) != null)
{
i++;
int lunghezza = line.Length;
Console.WriteLine(i);
System.Threading.Thread.Sleep(800);
string ris= traduttore.traduci(targetLanguage, line);
// Console.WriteLine(line);
// Console.WriteLine(ris);
// Console.Read();
// app = app + ris;
// System.Threading.Thread.Sleep(50);
File.AppendAllText(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt", ris + Environment.NewLine);
}
The code as it stands will skip over the first line, as you use ReadLine() twice prior to fist use.
You can restructure the code as
using (StreamReader reader = new StreamReader(#"C:\Users\lorenzov\Desktop\gi_pulito_neg.txt"))
using (StreamWriter writer = new StreamWriter(#"C:\Users\lorenzov\Desktop\gi_tradotto_neg.txt"))
{
string line = reader.ReadLine();
while(line != null)
{
System.Threading.Thread.Sleep(800);
string ris = traduttore.traduci(targetLanguage, line);
writer.WriteLine(ris);
line = reader.ReadLine();
}
}

Categories

Resources