Program that reads file and writes new info - c#

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

Related

Writing a certain amount of lines in a file C#

I am currently writing a program that takes in a file, loops through all of the lines.
The file contains a lot of variables + values in this format:
Message =
"alfjawejf1ij4l2jr183fhaalfjawejf1ij4l2jr183fhahalfjawejf1ij4l2jr183fhahalfjawejf1ij4l2jr183fhahalfjawejf1ij4l2jr183fhahh" //the string will encompass multiple
lines of length
Answer = ?
My program will modify the value within message and write it in a new file.
How do I store multiple lines of the value into one string (so I can modify it)?
I need it so that it recognizes "message", starts storing the next few lines, detects "answer" and stops.
For the string holding the message value, I believe some sort of concatenation will be used (concatenating multiple lines).
string[] file = System.IO.File.ReadAllLines(#path); //file is read
string pathNew = Path.GetDirectoryName(path) + "\\completed_" + Path.GetFileName(path);
using (StreamWriter writer = File.CreateText(#pathNew))
{
foreach (string line in file)
{
for (int i = 0; i < line.Length; i++)
{
if (line.Substring(0,6).Equals("Msg = "))
{
foreach (string msg in file)
{
}
}
}
}
}
You could create it pretty easily, if you would provide a method that returns an IEnumerable<string>, and then use the File.WriteAllLines( string, IEnumerable<string> ) utility method
A way you could do it could be
private IEnumerable<string> ReturnAllMessages( IEnumerable<string> lines )
{
bool isMessage = false;
foreach (var line in lines)
{
if (line.StartsWith('Msg ='))
{
isMessage = true;
// set a flag that the next lines are part of the message
// this would exclude the rest of the line from the results
// if you want it, you could use:
// yield return line.Substring('Msg ='.Length));
continue;
}
if (line.StartsWith('Answer ='))
{
// remove the flag
isMessage = false;
continue;
}
if (isMessage)
{
// yield a line that is a message
yield return line;
}
}
}
and then use the method in the following way
File.WriteAllLines( #newPath, ReturnAllMessages( File.ReadAllLines( #path ) ) );
(didn't really test the code though, so just use it as a reference ;) )
One way to do this would be to read all the text as a single string using File.ReadAllText, and then split it on "Message =" to get all the messages, and then split each message on "Answer = " to get the answer for each message (assuming the format is "Message = some message Answer = some answer Message = some other message Answer = some other answer").
It would be helpful if you included an actual sample from the file, since your code clearly was not written for the sample you've provided (there is no line where line.Substring(0,6).Equals("Msg = ") is true).
I've included a method in my sample below that creates a text file with a multi-line message, and then showed how you can read the message into a variable and display it in the console window.
Hope this helps:
private static void CreateFile(string filePath)
{
if (File.Exists(filePath)) File.Delete(filePath);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
var fileLines = new List<string>
{
"Message = ",
"I weigh nothing, but you can still see me.",
"If you put me in a bucket, I make the bucket lighter.",
"What am I?",
"Answer = A hole",
"Message = ",
"What’s the difference between",
"a hippo and a Zippo?",
"Answer = ",
"A hippo is really heavy, ",
"and a Zippo is a little lighter."
};
File.WriteAllLines(filePath, fileLines);
}
private static void Main()
{
// Set this to a file that doesn't exist or that you don't care about
var filePath = #"f:\private\temp\temp.txt";
// Create a file with multi-line messages
CreateFile(filePath);
// Read all the file text
var fileText = File.ReadAllText(filePath);
// Split it into the message/answers
var messageAnswers = fileText.Split(new[] {"Message ="},
StringSplitOptions.RemoveEmptyEntries);
// Split each message into a message/answer array
foreach (var messageAnswer in messageAnswers)
{
var parts = messageAnswer.Split(new[] {"Answer ="},
StringSplitOptions.RemoveEmptyEntries);
var message = parts[0].Trim();
var answer = parts.Length > 1 ? parts[1].Trim() : "";
Console.WriteLine(message);
var userResponse = Console.ReadLine().Trim();
if (userResponse.Equals(answer, StringComparison.OrdinalIgnoreCase))
{
Console.WriteLine("Correct!");
}
else
{
Console.WriteLine("The actual answer is: " + answer);
}
}
GetKeyFromUser("\nDone! Press any key to exit...");
}

writing in a file using C# StreamWriter

I was practicing to write into a file using c#
my code is not working (writing in file is not done)
{
int T, N; //T = testCase , N = number of dice in any Test
int index = 0, straight;
List<string> nDiceFaceValues = new List<string>(); //List for Dice Faces
string line = null; //string to read line from file
string[] lineValues = {}; //array of string to split string line values
string InputFilePath = # "E:\Visual Studio 2017\CodeJam_Dice Straight\A-small-practice.in"; //path of input file
string OuputFilePath = #
"E:\Visual Studio 2017\CodeJam_Dice Straight\A-small-practice.out"; //path of otput file
StreamReader InputFile = new StreamReader(InputFilePath);
StreamWriter Outputfile = new StreamWriter(OuputFilePath);
T = Int32.Parse(InputFile.ReadLine()); //test cases input
Console.WriteLine("Test Cases : {0}", T);
while (index < T) {
N = Int32.Parse(InputFile.ReadLine());
for (int i = 0; i < N; i++) {
line = InputFile.ReadLine();
lineValues = line.Split(' ');
foreach(string j in lineValues)
{
nDiceFaceValues.Add(j);
}
}
straight = ArrangeDiceINStraight(nDiceFaceValues);
Console.WriteLine("case: {0} , {1}", ++index, straight);
Outputfile.WriteLine("case: {0} , {1}", index, straight);
nDiceFaceValues.Clear();
}
}
what is wrong with this code?
how I fix it?
why its not working??
Note: I want to write in file line by line
What's missing is: closing things down - flushing the buffers, etc:
using(var outputfile = new StreamWriter(ouputFilePath)) {
outputfile.WriteLine("case: {0} , {1}", index, straight);
}
However, if you're going to do that for every line, File.AppendText may be more convenient.
In particular, note that new StreamWriter will be overwriting by default, so you'd also need to account for that:
using(var outputfile = new StreamWriter(ouputFilePathm, true)) {
outputfile.WriteLine("case: {0} , {1}", index, straight);
}
the true here is for append.
If you have opened a file for concurrent read/write, you could also try just adding outputfile.Flush();, but... it isn't guaranteed to do anything.

Creating a list of no duplicate string entries in a text file at C#

I'm a beginner at C# programming.
I wanted to create a text file to the desktop in C# Console, which is wanted to add my input new string value to the created text file's new line.
This is my work:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace noteonce
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine();
string wlist = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt";
TextWriter inject = new StreamWriter(wlist, true);
inject.WriteLine(newWord);
inject.Close();
Console.WriteLine("New word has been added! ");Console.ReadKey();
}
}
}
I created the file through the console, but I want each of my entered string to be unique, I did some look up on google but I'm so confused. I want the console to tell me that whether the new input already exists or not, If it is, to warn me as "It already exists! Input another word : ", If it does not exist, just to add it to the list. I need your assistance.
Thank you all for your attention. By the help of Mr.Ankitkumar Bhatt, This is my recent work :
static void Main(string[] args)
{
string wlist = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)+#"\list.txt";
FileStream create = File.Open(wlist, FileMode.Create);
create.Close();
for (int i = 0; i < 100; i++)
{
Console.WriteLine("New Word"+#" ("+(100-i)+") :");
string newWord = Console.ReadLine();
string FileContents = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt");
TextWriter inject = new StreamWriter(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt", true);
if (!FileContents.Contains(newWord))
{
inject.WriteLine(newWord);
inject.Close();
}
else
{
Console.WriteLine("It already exists!");
Console.ReadKey();
inject.Close();
}
}
}
But I want to point that, I want the program to recognize all of items in the list, by my last method, it quite works, but when I close, and open the program again, It doesn't give me the warning that New Word is already exist, doesn't add it to the file neither. How can I do the rest ?
In case of "no duplicate" please, have a look at HashSet<String>; you may find TextWriter and TextReader being too complex - try File.ReadLines(), File.AppendAllLines instead:
static void Main(string[] args) {
// better practice is paths combining
string path = Path.Combine(Environment.SpecialFolder.Desktop, "list.txt");
// unique (no duplicates) strings so far
HashSet<String> hash = new HashSet<string>(
File.ReadLines(path), // file to read from
StringComparer.OrdinalIgnoreCase); // let's ignore words' case ("World", "world")
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine().Trim(); // let's trim spaces: "world " -> "world"
if (!string.IsNullOrEmpty(newWord)) // let's not add an empty string
if (!hash.Contains(newWord)) {
// add new word to the end of file
File.AppendAllLines(path, new string[] {newWord});
Console.WriteLine("New word has been added!");
}
else
Console.WriteLine("It already exists! Input another word");
else
Console.WriteLine("We don't add empty lines.");
Console.ReadKey();
}
In case you want to add several words, one after one (put an empty line to exit):
static void Main(string[] args) {
// better practice is paths combining
string path = Path.Combine(Environment.SpecialFolder.Desktop, "list.txt");
// unique (no duplicates) strings so far
HashSet<String> hash = new HashSet<string>(
File.ReadLines(path), // file to read from
StringComparer.OrdinalIgnoreCase); // let's ignore words' case ("World", "world")
while (true) {
Console.WriteLine("New Word: ");
string newWord = Console.ReadLine().Trim(); // let's trim spaces: "world " -> "world"
if (string.IsNullOrEmpty(newWord))
break;
if (hash.Add(newWord)) {
File.AppendAllLines(path, new string[] {newWord});
Console.WriteLine("New word has been added!");
}
else
Console.WriteLine("It already exists! Input another word.");
}
Console.ReadKey();
}
before injecting word check the word exists or not like below
string FileContents = File.ReadAllText(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + #"\list.txt");
if (!FileContents.Contains(newWord))
{
// Add to file //
}
this can be accomplished in multiple ways. I will present a solution that most closely will work with your code. There is definitely a more elegant way to accomplish this, but this is a quick and dirty way to accomplish that.
one way is to have a foreach check from your text file so:
var isWordPresent = false;
var textLines = File.ReadAllLines(wlist);
foreach (var line in textLines) {
if (line.contains(newWord) {
isWordPresent = true;
}
}
if (isWordPresent == false) {
inject.WriteLine(newWord);
inject.Close();
isWordPresent = false; //added this portion incase you run this code in a while loop
//so you can reuse it. You would need to have the boolean reset to false
}
1) Read the file and write its content to a string[] (Array of string):
var lines = File.ReadAllLines(wlist , Encoding.UTF8);
2) Read your input and check for duplicates:
var input = Console.ReadLine();
if (lines.Contains(input)) {
//Warning message
} else {
//Success message
}

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

How can i read and display info from multiple text files in 1 message box C#?

So i have a application that uses check boxes and radio buttons to scan a computer for virus then have each anti virus create a log of its actions. What id like to do is (based on which check boxes (there's 5 total) are checked) have a message box pop up when its all done and have read each text file for a key word then read that line, for all 5 text files (if all 5 were created could be 1,2,3,4 or 5 of them). So when its all done it will just have 1 message box pop up with the info from all 5 text files 1 line each like "Panda found 5 viruses" next line "A Squared found 0 viruses" etc. then when the message box is closed, delete the text files. I know how to do this with 1 check box and 1 text file but i don't know how to do this with multiple check boxes and multiple text files. My single file reader works like this:
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file = new System.IO.StreamReader("C:\\Panda.txt");
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Number of files infected"))
{
MessageBox.Show("Panda " + line);
}
}
file.Dispose();
System.IO.File.Delete("C:\\Panda.txt");
any help would be nice thanks. OH and C# .net 2.0 ONLY please
You can use StringWriter to append the current line and display in Message Box at last
string FirstPanda = "C:\\FirstPanda.txt";
string SecondPanda = "C:\\SecondPanda.txt";
StringWriter writer = new StringWriter(); // System.IO;
System.IO.StreamReader file;
if (firstCheckBox.IsChecked)
{
if (File.Exists(FirstPanda))
{
file = new System.IO.StreamReader(FirstPanda);
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Number of files infected"))
{
writer.WriteLine("Panda " + line);
}
}
file.Close();
System.IO.File.Delete(FirstPanda);
}
}
if (secondCheckBox.IsChecked)
{
if (File.Exists(SecondPanda))
{
file = new StreamReader(SecondPanda);
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Number of files infected"))
{
writer.WriteLine("Panda " + line);
}
}
file.Close();
System.IO.File.Delete(SecondPanda);
}
}
MessageBox.Show(writer.ToString());
Hope this will help you
I hope I am understanding the question right, but if I rephrase it. You want to process the 5 files and when all done show a summary of what was found?
If so why not simply do this
public void ProcessFiles()
{
var resultText = new StringBuilder();
if (PandaCheckBox.Checked)
{
var result = DoPandaProcessing(); // Read file and do whatever here
resultText.Append(result.ResultMessage);
}
if (Process2CheckBox.Checked)
{
var result = DoProcess2Processing();
if (resultText.Length > 0)
{
resultText.Append(Environment.NewLine);
}
resultText.Append(result.ResultMessage);
}
MessageBox.Show(resultText.ToString());
}
And just because I don't like how you dispose (ie you don't on any exception), implement the methods like this
public ProcessResult DoPandaProcessing()
{
using (var file = File.OpenText("filename.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains("Number of files infected"))
{
return new ProcessResult { Status = Status.Success, ResultMessage = "Panda " + line };
}
}
return new ProcessResult { Status = Status.Failure, ResultMessage = "Panda: No result found!" }
}
}

Categories

Resources