-
File reading hlep
Hello!
Ok I was wondering what would be the best way to read a group of files and grab the 16th line from each? This is what I'm trying to do
I let the user pick the directory where the files are located and put the location in a var. I then get all the files names of a certain type
from the location. The 16th line of each file is what I want, it is a comma delimited line which I would like to split up either later on or
right then. So the question is do I do this all in one shot or is there a better way of looking at this?
Thanks for your help!
Stevish
-
Re: File reading hlep
Ok I have read each file into an array and now I want to read the file back out of the array one line at a time. Can
anybody point me on how to do this?
I'm looping through the array with a foreach, the code below just prints out the whole file that is stored in the array
to the textbox2. I can't really seem to find any code that works for reading the array item on line at a time, any help
would be great!
Code:
foreach (string s in fileNames)
{
textBox2.Text += File.ReadAllText(s) + fileNames.Length;
}
-
Re: File reading hlep
I just wrote up something real quick in Notepad++ that you can do that I would recommend.
Code:
foreach (string s in fileNames)
{
using (Streamreader sr = new Streamreader(s))
{
int lineNumber = 0;
string line = String.Empty;
while(!sr.EndOfStream)
{
line = sr.Readline();
++lineNumber;
textBox2.Text = String.Format("{0} - {1}", lineNumber, line);
}
}
}
This will still spit out all of the text in the file right away but you can change the "while" or add a condition in it to only display what you want. So if you want the 16th line to only show you can do something like:
Code:
if (lineNumber == 16)
{
//print the text to textBox
}
Also if you don't want to hard-code the 16 you can create a number box or whatever and use what ever number that is parsed from it.
-
Re: File reading hlep
If at all possible, I would avoid writing a program to do this. The shell is entirely sufficient:
Using Bash under Linux or Cygwin on Windows
Code:
for file in *.txt; do cat $file | sed -n '16p'; done
Under the Windows Powershell
Code:
foreach ($file in get-childitems *.txt) { (Get-Content $file)[15] }
Note that the lines are zero-indexed in powershell (line one is index zero), but one-indexed in sed (line one is index one).