How to count the text file which split with newline character - c#

I have a file text which splited by newline character. the text file such this:
merah.dc
kuning.dc
hijau.dc
biru.dc
orange.dc
mahopermanent.dc
I want to count them by splitting with a newline character. so, the count of them are 6. I could only do this with looping:
int count = 0;
string path = "directory\\admin.txt";
StreamReader moco = File.OpenText(path);
string s;
while ((s = moco.ReadLine())!= null)
{
count++;
}
I want to count them with a simple way like the PHP syntax:
<?php
$file = file("directory\\admin.txt");
$count = count($file);
echo $count;
?>
The above syntax able to counts them without looping. Just use file() and count(). is any function in C# which equals with that function ?

You can use ReadLines without loading whole file into the memory (of course this method can be useful if your file is large)
int count = File.ReadLines(filename).Count();

Step 1 : You can use ReadAllLines() function to get all Lines from the given file path as a String Array.
Step 2: you can invoke Length property on the obtained String Array to get the Count of Total Lines
Try This:
using System.IO;
String [] allLines=File.ReadAllLines(#"directory\admin.txt");
int length=allLines.Length;

You don't need to split them by a new character, use File.ReadAllLines (which returns an array of strins, each element is a line).
int lineCount = File.ReadAllLines("test.txt").Length;
If you want to use split, then:
int lineCount = File.ReadAllText("test.txt").Split('\n').Count();
ReadAllText returns a strin with the entire content of the file.

int count = File.ReadAllLines(#"directory\\admin.txt").Length;

You can Split() the textfile
StreamReader moco = File.OpenText(path);
string s;
string splitArray[] = s.Split('\n'); //Split on newline
int length = splitArray[].Length;

Related

Using C# append text to each end of line of a flat file

How to I append text to end of a line in a flat file using c#? Basically, I'd like to append row numbers at the end of each line.
Just a quick refactor of MasterXD's solution:
var linesInText = stringWithText.Split(Environment.NewLine);
StringBuilder stringWithRowNumbers = new StringBuilder();
var row = 1;
foreach (var line in linesInText)
{
stringWithRowNumbers.Append(line);
stringWithRowNumbers.Append(row++);
stringWithRowNumbers.Append(Environment.NewLine);
}
string result = stringWithRowNumbers.ToString();
Using StringBuilder for this is going to perform much better than simple string concatenation and is considered a best practice in this use case.
Here is a quick one line version using Linq's Enumerable.Select with index and String.Join Method (String, String[]) to rebuild the lines.
string path = "Path to your flat file";
var numberedText = String.Join(Environment.NewLine, File.ReadAllLines(path).Select((line, index) => string.Join(" ", line.Trim(), index + 1)));
Console.WriteLine(numberedText);
The resulting string will have row numbers at the end of each line.
By flat file i suppose you mean a normal text file?
Firstly you'd want to split a piece of text into it's lines. This is done by the following means:
string[] linesInText = stringWithText.Split('\n');
The character \n represents a new line. So everytime a 'new line' is present, split there. The the fucction Split seperates a string into parts, where the seperator is given as the input. The parts will then be made into a string array. In this case, all the lines in the text or string willbe turned into an array.
Now you'd want to add the numbers to the end of each line. This can be done in the following way:
string stringWithRowNumbers = "";
for (int i = 0; i < linesInText.Length; i++) // Go through all lines
{
stringWithRowNumbers = linesInText[i] + "YourNumbers" + "\n"; // The old/first line + your numbers + new line
}
Now you should have a string with numbers in the end of all lines.
I hope this helps.
EDIT: I just realized you asked for row numbers. Here's the correct code.
string stringWithRowNumbers = "";
for (int i = 0; i < linesInText.Length; i++) // Go through all lines
{
// The space is intentional. If there is no space, then the number will not have any space between itself and the line
stringWithRowNumbers = linesInText[i] + " " + (i + 1) + "\n"; // The old/first line + row number + new line
}

Read a file in specific location and replace all occurence of single quotes to &#39 in c#

I need to read a file in specific location and find all the occurence of single quote and replace it by &#39 in c#
string file = #"D:\MyDirectory\MyFile.po";
Say this is my file, I have to read this and replace all single quote by &#39.
You can use the System.IO Library, and read it into an array, replace each instance and then write it back to the file
string file = #"D:\MyDirectory\MyFile.po";
string[] allLines = System.IO.File.ReadAllLines(file);
for(int i = 0; i < allLines.GetLength(0); i++)
{
allLines[i] = allLines[i].Replace("'",#"&#39");
}
System.IO.File.WriteAllLines(file,allLines);
Alternatively you can use ReadAllText, which returns the entire file's contents as a single string, which removes the requirement to loop
string file = #"D:\MyDirectory\MyFile.po";
string allText = System.IO.File.ReadAllText(file);
allText = allText.Replace("'",#"&#39");
System.IO.File.WriteAllText(file,allText);

grab value from string in reverse order

I have file with txt content inside. Content is generated dynamicly and I want to read in reverse order, from end of file to the first matched semicolon, for example:
sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456
so I want to grab this 123456 integer, ofcourse this is generated content with random int length.
If you have always the searched text at the end of the string and after a semicolon you could use
string.LastIndexOf(';');
for example
string test = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
int pos = test.LastIndexOf(';');
if(pos >= 0)
string myText = test.Substring(pos+1);
What #Steve said, or just
string value = "sad12e1sadsadsadasdasd12e2q3312sdadasdasdasqe21231122123123asd1asda;123456";
string number = value.Split(';')[1];
though this doesn't handle the case where a semi-colon is missing.

Alternative to using substring? Substring makes it too easy to make repeating mistake when typing it

Is there a simplier, shorter cut way to this than using substring()? I'm trying to make it less error cuz it is too easy to make mistake when typing the LastIndexOf and Length, plus counter.
string filepath = "c:\folder1\folder2\folder3\file1.jpg";
string file = "";
file = filepath.SubString(
(filepath.LastIndexOf("\\")+1),
(filepath.Length - filepath.LastIndexOf("\\")+1)
);
I want to get this value "file1.jpg".
Thanks...
Yes, use Path.GetFileName
string filepath = "c:\folder1\folder2\folder3\file1.jpg";
string file = Path.GetFileName(filePath);
Another option for non path based records is using the String.Split function.
string longString = "The cat jump over the brown fox";
string[] splitString = longString.Split(new char[] {' '}); //Splits the string in to array elements wherever it see a space;
string lastWord = splitString[splitString.Length - 1]; //Could throw a error is the length is less than 1
string lastTwoWords = String.Join(" ", splitString.Skip(splitString.Length - 2)); //Could throw a error if the length is less than 2
This function may help you : Path.GetFileName()
There is GetFileNameWithoutExtension too if you don't need the file extension, and GetExtension to get the extension (:

Parse Text Row with Empty Spaces

I have a file, the text format is like this:
.640 .070 -.390 -.740 -1.030 -1.410 -1.780 -1.840
-1.360 -.360 .860 1.880 2.340 2.250 1.950 1.710
1.410 .700 -.300 -.840 -.280 1.020 1.860 1.460
.310 -.460 -.320 .350 1.020 1.650 2.430 3.070
2.840 1.440 -.460 -1.650 -1.520 -.520 .250 .190
-.420 -.870 -.800 -.280 .570 1.660 2.500 2.220
.520 -1.560 -2.530 -2.030 -1.200 -1.060 -1.230 -.600
.990 2.300 2.180 .940 -.090 -.140 .320 .470
.330 .420 .830 1.080 1.090 1.530 2.740 3.800
3.410 1.610 -.150 -.900 -1.120 -1.640 -2.140 -1.590
.210 2.210 3.290 3.170 2.380 1.880 2.530 4.210
5.280 3.820 -.040 -3.670 -4.190 -1.260 2.930 5.740
5.980 3.920 .540 -2.890 -5.010 -4.780 -2.150 1.640
4.670 5.540 4.230 1.950 .120 -.470 -.010 .340
-.710 -2.940 -4.070 -1.810 3.000 6.590 6.140 2.750
-.490 -2.460 -4.180 -5.660 -4.800 -.560 4.510 6.630
5.140 2.860 2.230 2.510 1.670 -.440 -2.030 -2.330
Note that there are a lot of white characters between one value and another.
I tried to read each line, and then split the line according to a ' ' character. My code is something like this:
public List<double> Parse(StreamReader sr)
{
var dataList = new List<double>();
while (sr.Peek() >= 0)
{
string line = sr.ReadLine();
if (lineCount > 1)
{
string[] columns = line.Split(' ');
for (var j = 0; j < columns.Length; j++)
{
dataList.Add(double.Parse(columns[j]) ));
}
}
}
return dataList ;
}
The problem with the above code is that it is only able to handle the case where values are separated by a single white character.
Any idea ?
The simplest way is probably to use an overload of String.Split which includes a StringSplitOptions parameter, and specify StringSplitOptions.RemoveEmptyEntries.
I would also personally just call ReadLine until that returned null, rather than using TextReader.Peek. Aside from anything else, it's more general - it will work even if the underlying stream (if any) doesn't support seeking.
Before you do the split, replace all multi spaces with a single space, something like:
line = System.Text.RegularExpressions.Regex.Replace(line, #" +", #" ");
You may use the simple one line code for this. Let your text is in the string named input.
string[] values = System.Text.RegularExpressions.Regex.Split(input, #"\s+");
You will get all values in a string array simply

Categories