Reading specific number of lines from text file in c# - c#

I'm using the following StreamReader to read from text file
string temp = fs.ReadToEnd ();
readlines[i] = temp;
I want to read a specific number of lines from the text file (let we say, from line number 1 until line number 300 only), then write the lines into one element of array. Could anyone help please? thanks in advance.

If you want to skip n first lines and read p lines from there :
var lines = System.IO.File.ReadLines(path).Skip(n).Take(p).ToArray()

Tried with a simple text file.
var lines = File.ReadLines("yourfile").Take(300);
readlines[i] = string.Join("-", lines);

Use the ReadLine method and add a counter and increase it by line and when you hit 300 do a break out of the loop

Related

Read Text with conditions

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.

How a can split file line with many spaces in C# asp?

I need your help. I have a txt file with many lines of information.
The headers of the file are
Date ReferenceNumber Description
13/06/2013 00000081985 TRF DESDE OTRO BCO 00000000000000972353
0105
Mount Money +50.000,00 344.514,74
Between Description and Mount are many spaces
Here's a image of the file
I need split this line to get all the attributes by separate.
I need, Date = 13/06/2013, ReferenceNumber = 00000081985, ....
I'm trying to use split C# function to separate by (' ') but i only can get the 2 first attributes =(
I hope you can help me! Thanks a lot.
You may want to look to see what the length of each field is because it does look like fixed length data. If so use the String.Substring Method, using the starting position and the max length of each field as inputs.
This looks like you're trying to deal with a fixed length file, which is essentially a file with data that is split based on its physical location in the file (each piece of data is expected to occupy a specific number of characters). Seems to be one of those lesser known functions, but check out TextFieldParser. It's a .NET class specifically made for this sort of thing.
Specifically, check out the property TextFieldType, which can be set to FixedWidth and given a width of each of those fields. Should do exactly what you want.
You can try to do something like this:
StreamReader sr = new StreamReader("path to text file");
string s = sr.ReadToEnd();
s = s.Replace(' ', '!'); //change the space sign with other sign
List<string> strList = s.Split('!').ToList();
strList.RemoveAll(t => t == "");
I know the solution isn't best but I hope it will help you.

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.

Editing specific lines in a text file using c#

I'm currently trying to edit a text file in c#. This text file is created in a previous form and consists of the following :
Date Of Birth = 01/01/1980
Age = 31
Total = 40985
required1 =
required2 =
required3 =
This text file is only 13 lines long, basically i want to ignore the first three lines then edit the following 10 lines. I tried initially with the following code but the obvious flaw is appending to the file:
List<string> newlines = new List<string>();
newlines.Add(Convert.ToString(required1));
newlines.Add(Convert.ToString(required2));
newlines.Add(Convert.ToString(required3));
System.IO.File.AppendAllLines(filepath);
I'm thinking using streamreader reading all the lines but how to edit the 3rd line onwards is something of a mystery, yes I'm new using c# any help is greatly appreciated.
Since your file is small, you can load it whole into memory. Then work with that and save it, completely overwriting the whole file:
string[] lines = File.ReadAllLines(fileName);
// modify the lines
File.WriteAllLines(fileName, lines);

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