How to get number of rows in file in C#? - c#

I need to initialize 2D array and first column is every row in a file. How do I get the number of rows in a file?

You could do:
System.IO.File.ReadAllLines("path").Length
Edit
As Joe points out, I left out all the standard error handling and didn't show you would then use this same array to process in the rest of your code.

From MSDN:
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();

You would have to open the file reading in each line to get the count:
var lines = File.ReadAllLines(filename);
var count = lines.Length;

int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("c:\\t1.txt");
while((line = file.ReadLine()) != null)
{
counter++;
}
file.Close();
counter will give you number of lines. you can insert line into your array as well withthe loop.

There may be a more efficient way for larger files, but you could start with something like:
int l_rowCount = 0;
string l_path = #"C:\Path\To\Your\File.txt";
using (StreamReader l_Sr = new StreamReader(l_path))
{
while (l_Sr.ReadLine())
l_rowCount++;
}

It would probably be more useful for you to actually open the file, read the lines into a List, then create your 2D array.
List<string> lines = new List<string>()
using(System.IO.StreamReader file = new System.IO.StreamReader(fileName))
{
while(!file.EndOfStream) lines.Add(file.ReadLine());
}
You can then use your lines list to create your array.

could you go with something more exotic like a linq statement
Count * from textfile
something like that?

Related

Skip lines and start read from specific line C# unity

I am reading from a file and I am trying to skip first two lines and start reading from the third one. I've checked other questions which were answered but none of them worked on unity for some reason. I get several errors however it should work.
StreamReader reader = new StreamReader(path);
string line = "";
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
....
}
If I understand correctly, we can try to use File.ReadAllLines which will return all line of text content from your file text and then start reading on the third line (array start as 0, so that the third line might be contents[2]).
var contents = File.ReadAllLines(path);
for (int i = 2; i < contents.Length; i++)
{
string[] words = contents[i].Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
}
If we know the Encoding of the file we can try to set Encoding to the second parameter in File.ReadAllLines
Similar to D-Shih's solution, is one using File.ReadLines, which returns an IEnumerable<string>:
var lines = File.ReadLines(path);
foreach (string line in lines.Skip(2))
{
string[] words = line.Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
// etc.
}
The benefit of this approach over D-Shih's is that you don't have to read the entire file into memory at once to process it, so this solution is analogous to your existing solution's use of StreamReader.
As a solution for directly fixing your problem, you just need to call ReadLine twice before getting into the loop (to skip the two lines), though I'd argue the solution above is more legible:
using (StreamReader reader = new StreamReader(path))
{
string line = "";
// skip 2 lines
for (int i = 0; i < 2; ++i)
{
reader.ReadLine();
}
// read file normally
while ((line = reader.ReadLine()) != null)
{
string[] words = line.Split(' ');
string type = words[0];
float x = float.Parse(words[1]);
....
}
}
Notice that I've also wrapped the reader in a using, so that the file handle will be closed & disposed of once the loop completes, or in case of an exception being thrown.

count lines from text file and count it in 1 line

So what I want to do its count lines from a text file and count them in 1 line on the console window. This is what I have now, it works but it writes lot of lines to the console and I want it to change the count on 1 line every second.
long lines = 0;
using (StreamReader r = new StreamReader("text.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
count++;
Console.Title = "Count: " + lines;
Console.WriteLine(Console.Title);
}
}
You can use File.ReadAllLiness(<filePath>).Count() to get count of lines in text file.
Console.WriteLine(File.ReadAllLiness("text.txt").Count())
Your code is not working because you are printing lines variable which is assigned as 0 at the beginning, but not updated anywhere.
Either try my first solution or use lines variable instead of count in your existing program and print it out of while loop
long lines = 0;
using (StreamReader r = new StreamReader("text.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
Console.WriteLine(++lines); //One line solution
}
}
You should take a look at this topic:
How can I update the current line in a C# Windows Console App?
It is possible to update the current line. All you need to add is a logic to only do it once per second.
Maybe something like this:
long lines = 0;
var lastSecond = DateTime.Now.Second;
using (var r = new StreamReader("text.txt"))
{
string line;
while ((line = r.ReadLine()) != null)
{
lines++;
Console.Title = "Count: " + lines;
if(lastSecond != DateTime.Now.Second)
Console.Write("\r{0} ", Console.Title);
lastSecond = DateTime.Now.Second;
}
Console.WriteLine(""); // Create new line at the end
}
There will be nicer ways to update once per second but the main problem seems to be how to update the current console output.

Extracting the first 10 lines of a file to a string

public void get10FirstLines()
{
StreamReader sr = new StreamReader(path);
String lines = "";
lines = sr.readLine();
}
How can I get the first 10 lines of the file in the string?
Rather than using StreamReader directly, use File.ReadLines which returns an IEnumerable<string>. You can then use LINQ:
var first10Lines = File.ReadLines(path).Take(10).ToList();
The benefit of using File.ReadLines instead of File.ReadAllLines is that it only reads the lines you're interested in, instead of reading the whole file. On the other hand, it's only available in .NET 4+. It's easy to implement with an iterator block if you want it for .NET 3.5 though.
The call to ToList() is there to force the query to be evaluated (i.e. actually read the data) so that it's read exactly once. Without the ToList call, if you tried to iterate over first10Lines more than once, it would read the file more than once (assuming it works at all; I seem to recall that File.ReadLines isn't implemented terribly cleanly in that respect).
If you want the first 10 lines as a single string (e.g. with "\r\n" separating them) then you can use string.Join:
var first10Lines = string.Join("\r\n", File.ReadLines(path).Take(10));
Obviously you can change the separator by changing the first argument in the call.
var lines = File.ReadAllLines(path).Take(10);
You may try to use File.ReadLines. Try this:-
var lines = File.ReadLines(path).Take(10);
In your case try this as you want the first 10 lines as a single string so you may try to use string.Join() like this:
var myStr= string.Join("", File.ReadLines(path).Take(10));
StringBuilder myString = new StringBuilder();
TextReader sr = new StreamReader(path);
for (int i=0; i < 10; i++)
{
myString.Append(sr.ReadLine())
}
String[] lines = new String[10];
for (int i = 0; i < 10; i++)
lines[i] = sr.readLine();
That loops ten times and places the results in a new array.
public void skip10Lines()
{
StringBuilder lines=new StringBuilder();
using(StreamReader sr = new StreamReader(path))
{
String line = "";
int count=0;
while((line= sr.ReadLine())!=null)
{
if(count==10)
break;
lines.Append(line+Environment.NewLine);
count++;
}
}
string myFileData=lines.ToString();
}
OR
public void skip10Lines()
{
int count=0;
List<String> lines=new List<String>();
foreach(var line in File.ReadLines(path))
{
if(count==10)
break;
lines.Add(line);
count++;
}
}
Reason beeing is that the nested operators File.ReadLines(path).Take(10).ToList(); will do the following truly:
string[] lines = File.ReadLines(path); // reads all lines of the file
string[] selectedlines = lines.Take(10); // takes first 10 line s into a new array
List<String> LinesList = selectedlines.ToList();
Especially the first part is cumbersome as it reads the full file into an enumerable of lines. This eats Performance and Memory. The question poster asked specifically for large files.
for this reason, I would rather recommend:
/// <summary>
/// This function loads and returns the first x lines from a file
/// </summary>
/// <param name="path">The path to the file to read</param>
/// <param name="amountOfLines">the number of lines which should be read</param>
/// <param name="encoding">optional value, which specifies the format in which the text file is saved</param>
/// <returns></returns>
public List<string> GetFirstXLines(string path, int amountOfLines, Encoding encoding = null)
{
// if no encoding is set, try the default encoding (File Format)
if (encoding == null) encoding = Encoding.Default;
// create list which will be filled with the lines and returned later
List<string> lines = new List<string>();
// wrap streamreader around so it gets closed+disposed properly later
using (StreamReader reader = new StreamReader(path, encoding))
{
// loop x times to get the first x lines
for (int i = 0; i < amountOfLines; i++)
{
// read the next line
string line = reader.ReadLine();
// if the line is null, we are at the end of file, break out of the loop
if (line == null) break;
// if the line was not null, add it to the lines list
lines.Add(line);
}
}
// return the lines
return lines;
}
In Groovy, a JVM based language, one approach is:
def buf = new StringBuilder()
Iterator iter = new File(path).withReader{
for( int cnt = 0;cnt < 9;cnt++){
buf << it.readLine()
}
}
println buf
Since, there is no 'break' from a closure, the loop is nested within the closure, and thereby the resource handling is taken care of by the Groovy runtime.

How to read from a file using C# code?

I have a file contains two lines . and in which line there is a double parameter .
I want to read both lines from the file and save them in an array of doubles .
I used the C# code below , but It doesn't work . It doesn't read anything and the array is empty after running the code .
Anybody has any idea where did I do wrong ?
Thanks for help .
private FileStream input;
double[] arr;
int i = 1;
input = new FileStream(Application.StartupPath+"\\City.txt", FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(input);
while (!reader.EndOfStream)
{
arr[i] = Convert.ToDouble(reader.ReadLine());
i++;
}
reader.Close();
This is a complete example of what you are doing.
string line;
List<double> values = new List<double>();
string path = Path.Combine(Application.StartupPath, "City.txt");
System.IO.StreamReader file = new System.IO.StreamReader(path);
while((line = file.ReadLine()) != null)
{
values.Add(double.Parse(line));
}
file.Close();
Based on "How to: Read a Text File One Line At a Time (MSDN)"
try this approach
using (StreamReader sr = File.OpenText(Application.StartupPath+"\\City.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
arr[i] = Convert.ToDouble(line);
i++;
}
}
and you should at least initialize arr: arr = new double[_size] and i should be zero because arrays in c# are zero based. And better use generic collection like List<T>(List<double> in this case).
The issue is while (!reader.EndOfStream) because when you initially read it in the position is at the end of the file. This is solidified by the fact that the line arr[i] should fail because you've not initialized the array (in fact, it shouldn't even compile...). So, how about this:
double[] arr = new double[2];
...
reader.BaseStream.Position = 0;
while (!reader.EndOfStream)
{
arr[i] = Convert.ToDouble(reader.ReadLine());
i++;
}
However, a more straight forward approach would be something like this:
var arr = new List<double>();
var lines = File.ReadAllLines(Application.StartupPath+"\\City.txt");
foreach (var l in lines)
{
arr.Add(Convert.ToDouble(l));
}
return arr.ToArray();
Another option is use File.ReadAllLines, considering that file size is small.
string[] stringDoubles = File.ReadAllLines(path, Encoding.UTF8);
for(int i=0;i<stringDoubles.Length;i++)
arr[i] = Convert.ToDouble(stringDoubles[i]);
The code as you posted will not compile, because you have not initialized your array, as well as having a visibility modifier on your FileStream. I'd guess this code is from two different locations in your project.
However, there's a much simpler way to do this: File.ReadAllLines
string path = #"c:\dev\text.txt"; //your path here
string[] lines = File.ReadAllLines(path);
double[] doubles = new double[2];
for (int i = 0; i < doubles.Length; i++)
{
double d;
if (double.TryParse(lines[i], out d))
doubles[i] = d;
}

How do I move items up/down in text file

How do I move items/values up and down a text file. At the moment my program reads a text file, an uses a while to make sure it stop when there is no more lines to read. I used an if statement to check if counter equals the line of the value I want to move. I am stuck not sure how to continue from here.
_upORDown = 1;
using (StreamReader reader = new StreamReader("textfile.txt"))
{
string line = reader.ReadLine();
int Counter = 1;
while (line != null)
{
if (Counter == _upORDown)
{
//Remove item/replace position
}
Counter++;
}
}
You can read the file in memory, move the line to where you need it, and write the file back. You can use ReadAllLines and WriteAllLines.
This code moves the string at position i up by one line:
if (i == 0) return; // Cannot move up line 0
string path = "c:\\temp\\myfile.txt";
// get the lines
string[] lines = File.ReadAllLines(path);
if (lines.Length <= i) return; // You need at least i lines
// Move the line i up by one
string tmp = lines[i];
lines[i] = lines[i-1];
lines[i-1] = tmp;
// Write the file back
File.WriteAllLines(path, lines);
#dasblinkenlight's answer, using LINQ:
string path = "c:\\temp\\myfile.txt";
var lines = File.ReadAllLines(path);
File.WriteAllLines(
path,
lines.Take(i).Concat(
lines.Skip(i+1)
)
);
This deletes the line at position i (zero-based) and moves the other lines up.
Adding to a new line:
string path = "c:\\temp\\myfile.txt";
var lines = File.ReadAllLines(path);
var newline = "New line here";
File.WriteAllLines(
path,
lines.Take(i).Concat(
new [] {newline}
).Concat(
lines.Skip(i+1)
)
);

Categories