Read Text with conditions - c#

sample1.txt
ID Name Age
1 Amila 31
2 Jaya 28
3 Sahan 24
4 Ishara 21
This is my sample1.text file with 3 columns. I want to read the file and write only persons with age greater than 25.
Can you please help to with the best way to do this.
Thanks

Use the string.Split method to add your elements to an array or list.
For for tabs it'd look like yourString.Split("\t") and for commas yourString.Split(",")
More info on the Split here: https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netframework-4.8

How I would tackle this
Read the lines from the sample file using File.ReadAllLines(#"FilePath") and store them in a list.
Create a StreamWriter for writing the values you want to the Output File
If you want the headers in the output file then write the headers and then remove them from the list.
Have a loop that will split the line with line.split('\t'), check the age for that line, and write the line if it matches the condition using output.writeline("Stuff to write")
After Looking at Your Progress
Move the using(var writer=new StreamWriter(WritePath)) to above string s =""; since you are only writing the last line of the original file.
You are basically overwriting the file with each line read instead of appending.
Inside the while loop you can check the age and then write the lines you want in the format you want.

Related

C# parsing out data line by line by character location from txt file

Just looking to see what the best way to approach the following situation would be.
I am trying to make a small job that reads in a txt file which has a thousand or so lines;
Each line is about 40 characters long (mostly numbers, some letter identifiers).
I have used
DataTable txtCache = new DataTable();
txtCache.Columns.Add(new DataColumn("Column1"));
string[] lines = System.IO.File.ReadAllLines(FILEcheck.Properties.Settings.Default.filePath);
foreach (string line in lines)
{
txtCache.Rows.Add(line);
}
However, what I really want to do is a bit confusing and hard to explain so i'll do my best. An example of line is below:
5498494000584454684840}eD44448774V6468465 Z
In the beginning of that long string is a "84", and then a "58" a little bit later. I need to do a comparison on these two numbers. They could be anything, but only a few combinations are acceptable in the file. They will always be in the same spot and same amount of characters (so it will always be 2 numbers and always in the 4-5 location). So I want to have 3 columns. I want the full string in 1 column, and then the 2 individual smaller numbers in columns of themselves. I can then compare them later on, and if there is an issue, I can return the full string which caused the issue.
Is this possible? I am just not sure how to parse out a substring based on character location and then loading it into a datatable.
Any advice would be appreciated. Thank you,
You could create the columns for each of items you are looking to store (whole string, first number, second number), and then add a row for each of the lines in the input file. You could just use the substring method to parse out the two digit numbers and store them. To do your analysis, you could parse the numbers out from the strings, or whatever else you need to do.
lines[0].Substring(3,2) will give you "84" in your above example. If you want the int, you could use Int32.Parse(lines[0].Substring(3,2))
Substring reference: http://msdn.microsoft.com/en-us/library/aka44szs%28v=vs.110%29.aspx

Reading All contents of a text document line by line

I have a text document with multiple lines which contain a persons name, age, favourite number and their favourite activity.
For example:
Line 1: Josh 30 100 Likes to play soccer.
Line 2: May 21 3 Likes to dance.
etc.
I have a message box which I would like to show their name, age, favourite number and activity one by one.
How can I do this and how can I pick up their number as integers too? thanks.
Sorry I have no code as I don't know what to do but I was thinking of using streamreader.
Here are the tools you need for your task:
For reading the lines of the file (Blorgbeard's suggestion):
string[] lines = File.ReadAllLines("file.txt");
For getting the values of each line (assuming that the names can be one-word only):
string[] values = line.Split(new char[]{' '},4);
For converting a value from String to Integer:
int intValue = Convert.ToInt32(strValue);

Extract data from a text file using a RegEx

I am trying to write a RegEx to extract data from a file.
The file looks like the following:
"a123 100 Start"
"a123 101 Today"
"a123 101 Tomorrow"
"a123 102 End"
The file contains multiple lines of records just like the one above. In each line of the file there is a code on a fixed position (100 - start of record, 101 - record detail, 102 - end of record). I would like to extract from that file a structure like a List<List<string>> where the outer list will store all the groups of records that are in the file.
My first approach was to parse this file with a foreach but I think there should be a way to achieve this with a RegEx. And being that I would like to expand my RegEx knowledge, I think that is a great example for me.
Is it possible for such data to be parsed with a RegEx? If so, can someone help out with the RegEx itself?
Thanks!
If your file has this specific structure, you do not need to use Regex. Just use Split(" ") and the result array for each line.
Regex has performance penalties.
But if you like to use Regex anyway, you can use Regex.Match(line, "[\S]+ [\S]+ [\S]+") for this file structure.

LINQ; Select Groups of Lines from a Text File

Greeting Gurus, I have a text file with groups of text that I need to seperate into seperate string arrays. How do I group these using the line "start:" as the delimiter? (groups may contain differing line counts but the all begin with "start:". Is this a job that LINQ can accomplish? (Each line has seperate data, it does not look that way in the preview).
List<string> lines = File.ReadAllLines(#"C:\test.txt").ToList();
start: data 1
boy: data 2
great: data 3
start: data 7
boy: data 8
great: data 9
girl: data 10
may be there is a linq solution but when you simply can handle this with for loops, I think there isn't any need to linq, for example I think bellow code done what you want:
var groups = new List<List<string>>();
foreach (var line in lines)
{
if (line.StartsWith("Start:"))
{
groups.Add(new List<string>());
}
groups[groups.Count - 1].Add(line);
}
I'd assumed first line of your file starts with Start: else you should skip first lines until reach the first start:.
File.ReadAllText(#"C:\test.txt").split("start:");
Will read the file and split the file into an aray of string on the start: tag.

How to display char in grid lines using c#

I am working on a desktop application develop in C#. what i want to do is to:
Open a text file(.txt) Read Data Line By Line Create a grid type structure(i.e combination of
horizontal and vertical line) Then take first line and display its each char in single cell And the take second line and display its each char in single cell and so on.
Since i am beginner so i don't have any idea that how to acheive this. I only want some suggestions and guidance.
Well, this is actually easy to do provided you compose the correct items together to get your result.
You'll want to look up File operations, string manipulation (as well as the knowledge that a string is nothing but an enumerable of chars), and then some simple looping to get what you want.
At a high level, you'll just be needing to get the math right to display your set of text as a grid in X columns by Y rows.
Use File.ReadAllLines(). It will give you and array of strings - line by line.
For each string returned by ReadAllLines use string.ToCharArray. It will give you an array of symbols in string.
Update:
Number of columns in grid will be equal to max length of char array. Number of rows - to number of lines. Hope, I understood your task correctly.
Sounds like a homework problem?
Use the File class to read your text file. As far as printing the output to the screen, you have many options...if you're building a console application the you could just write characters to the output using the Console methods.
Hint: to split each line of text into characters, use the ToCharArray() method on the String class.
here is how you can read from a text file line by line
int counter = 0;
string line;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader("c:\\test.txt");
while((line = file.ReadLine()) != null)
{
Console.WriteLine (line);
counter++;
}
file.Close();
// Suspend the screen.
Console.ReadLine();
http://msdn.microsoft.com/en-us/library/aa287535(v=vs.71).aspx

Categories