I am trying to get a list of lines that are before lines that contains a specific word. Here is my script:
private static void Main(string[] args)
{
int counter = 0;
string line;
System.IO.StreamReader file = new System.IO.StreamReader("E:\\overview2.srt");
List<string> lines = new List<string>();
while ((line = file.ReadLine()) != null)
{
if (line.Contains("medication"))
{
int x = counter - 1;
Console.WriteLine(x); // this will write the line number not its contents
}
counter++;
}
file.Close();
}
Using LINQ method syntax:
var lines = File.ReadLines("E:\\overview2.srt")
.Where(line => line.Contains("medication"))
.ToList();
and LINQ keyword syntax:
var lines = (
from line in File.ReadLines("E:\\overview2.srt")
where line.Contains("medication")
select line
).ToList();
If you need an array, use .ToArray() instead of .ToList().
Also, if all you need is to iterate once over the lines, don't bother with ToArray or ToList:
var query =
from line in File.ReadLines("E:\\overview2.srt")
where line.Contains("medication")
select line;
foreach (var line in query) {
Console.WriteLine(line);
}
This code will show all lines immediately before any line that contains your search text.
private static void Main(string[] args)
{
string cacheline = "";
string line;
System.IO.StreamReader file = new System.IO.StreamReader("C:\\overview2.srt");
List<string> lines = new List<string>();
while ((line = file.ReadLine()) != null)
{
if (line.Contains("medication"))
{
lines.Add(cacheline);
}
cacheline = line;
}
file.Close();
foreach (var l in lines)
{
Console.WriteLine(l);
}
}
It's difficult to tell from your question where you're looking for ALL lines before the found line or just a single line. (You would have to deal with the special case where the search text is found on the first line).
You could create a Queue<string>. Add each line to it as you pass over it. If it has more than the required number of lines in it dequeue the first item. When you hit your required search expression the Queue<string> contains all the lines you will need to output.
Or if memory is no object, you could just use File.ReadAllLines (see http://msdn.microsoft.com/en-us/library/system.io.file.readalllines.aspx) and index away into an array.
try this:
int linenum = 0;
foreach (var line in File.ReadAllLines("Your Address"))
{
if (line.Contains("medication"))
{
Console.WriteLine(string.Format("line Number:{} Text:{}"linenum,line)
//Add to your list or ...
}
linenum++;
}
Related
i am trying to editing only one column within my csv. however the code does not seem to affect the file. the changes im trying to make is to change to separate the 4th column data with a comma.
class Program
{
static void Main(string[] args)
{
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "kaviaReport 02_08_2016.csv");
var fileContents = ReadFile(filePath);
foreach (var line in fileContents)
{
Console.WriteLine(line);
}
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
public static IList<string> ReadFile(string fileName)
{
var results = new List<string>();
int lineCounter = 0;
string currentLine = string.Empty;
var target = File
.ReadAllLines(fileName);
while ((currentLine = fileName) != null)//while there are lines to read
{
List<string> fielded = new List<string>(currentLine.Split(','));
if (lineCounter != 0)
{
//If it's not the first line
var lineElements = currentLine.Split(',');//split your fields into an array
var replace = target[4].Replace(' ', ',');//replace the space in position 4(field 5) of your array
results.Add(replace);
//target.WriteAllLines(string.Join(",", fielded));//write the line in the new file
}
lineCounter++;
File.WriteAllLines(fileName, target);
}
return results;
}
}
The current code has some errors.
The biggest one is the assignement of currentLine to fileName. This, of course is meaningless if you want to loop over the lines. So you need a foreach over the read lines.
Then inside the loop you should use the variable lineElements to get the 5 column available after the splitting of the currentLine.
Finally the rewrite of the file goes outside the loop and should use the result list.
// Loop, but skip the first line....
foreach(string currentLine in target.Skip(1))
{
// split your line into an array of strings
var lineElements = currentLine.Split(',');
// Replace spaces with commas on the fifth column of lineElements
var replace = lineElements[4].Replace(' ', ',');
// Add the changed line to the result list
results.Add(replace);
}
// move outside the foreach loop the write of your changes
File.WriteAllLines(fileName, results.ToArray());
Something has occured to my mind while writing this code. It is not clear if you want to rewrite the CSV file with only the data in the fifth column expanded with commas or if you want to rewrite the entire line (also column 0,1,2,3,4 etc..) in this latter case you need a different code
// Replace spaces with commas on the fifth column of lineElements
// And resssign the result to the same fifth column
lineElements[4] = lineElements[4].Replace(' ', ',');
// Add the changed line to the result list putting the comma
// between the array of strings lineElements
results.Add(string.Join(",", lineElements);
while ((currentLine = fileName) != null) will set currentLine = fileName which will make the line always true and make a infinite loop
I would write it as a for loop instead of a while
public static IList<string> ReadFile(string fileName)
{
var target = File.ReadAllLines(fileName).ToList();
// i = 1 (skip first line)
for (int i = 1; i < target.Count; i++)
{
target[4] = target[4].Replace(' ', ','); //replace the space in position 4(field 5)
}
File.WriteAllLines(fileName, target);
// Uncomment the RemoveAt(0) to remove first line
// target.RemoveAt(0);
return target;
}
what i'm trying to do here is to delete the longest line from a txt file. Code does it's job, but i also need it to delete multiple "longest lines" and blank lines as well. Any ideas on how to do it?
Code is in C#
namespace _5_2
{
//------------------------------------------------------------
class Program
{
const string CFd = "..\\..\\U1.txt";
const string CFr = "..\\..\\Results.txt";
static void Main(string[] args)
{
int nr;
Read(CFd, out nr);
Print(CFd, CFr, nr);
Console.WriteLine("Longest line nr. {0, 4:d}", nr + 1);
Console.WriteLine("Program done");
}
//------------------------------------------------------------
/** Finds number of the longest line.
#param fv - text file name
#param nr - number of the longest line */
//------------------------------------------------------------
static void Read(string fv, out int nr)
{
string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
int ilgis = 0;
nr = 0;
int nreil = 0;
foreach (string line in lines)
{
if (line.Length > ilgis)
{
ilgis = line.Length;
nr = nreil;
}
nreil++;
}
}
static void Print(string fv, string fvr, int nr)
{
string[] lines = File.ReadAllLines(fv, Encoding.GetEncoding(1257));
int nreil = 0;
using (var fr = File.CreateText(fvr))
{
foreach (string line in lines)
{
if (nr != nreil)
{
fr.WriteLine(line);
}
nreil++;
}
}
}
}
}
I would suggest using LINQ. Take advantage of the .Max extension method and iterate over the string array.
string[] lines = { "1", "two", "three" };
var longestLine = lines.Max(line => line.Length);
var revised = lines.Where(line => line.Length < longestLine).ToArray();
The revised variable will contain a string array that excludes the lines with the longest line count.
Read lines, filter out empty lines and the 10 longest lines, write lines:
string[] lines = File.ReadAllLines(inputFile, Encoding.GetEncoding(1257));
var filtered = lines
.Where(line => line.Length > 0) // remove all empty lines
.Except(lines.OrderByDescending(line => line.Length).Take(10)); // remove 10 longest lines
File.WriteAllLines(outputFile, filtered);
You could identify the longest line, and then loop through the list, deleting all of that length. To also delete empty ones, you could test against String.IsNullOrWhiteSpace.
Something like (pseudocode):
foreach (string line in lines)
{
if (String.IsNullOrWhiteSpace(line))
{
lines.Delete(line);
Continue;
}
if (line.Length >= longestLine) // ">=" instead of "==" just to be on the safe side
{
lines.Delete(line);
}
}
This question already has answers here:
Edit a specific Line of a Text File in C#
(6 answers)
Closed 8 years ago.
Could anyone tell me how to edit a specific line in a text document?
For instance, lets say that my document contains two phone numbers:
"0889367882
0887343160"
I want to delete the second number and write a new phone number, how can I do that?
I am printing the text in the document, but i don't know how to choose which line to edit
and how to do that.
string path = #"C:\Users\...\text1.txt";
string[] lines = File.ReadAllLines(path);
int i = 0;
foreach (var line in lines)
{
i++;
Console.WriteLine("{0}. {1}", i, line);
}
Thanks!
Simply use string.replace.
Like this:
if(line.Contains("0887343160")
line = line.Replace("0887343160", "0889367882");
and after replacing, write all lines back in the file.
A better version would be to iterate the lines in the file rather than loading the whole file lines to memory. Hence using an iterator would do best here.
We do a MoveNext() on the iterator object and write the current line pointed by the iterator to the file after executing the necessary replace logic.
StreamWriter wtr = new StreamWriter("out.txt");
var e = File.ReadLines(path).GetEnumerator();
int lineno = 12; //arbitrary
int counter = 0;
string line = string.Empty;
while(e.MoveNext())
{
counter++;
if(counter == lineno)
line = replaceLogic(e.Current);
else
line = e.Current;
wtr.WriteLine(line);
}
wtr.Close();
Solution 1: if you want to remove the Line based on user input String (matches with one of the line from file) you can try this.
string path = #"C:\Data.txt";
string[] lines = File.ReadAllLines(path);
String strRemove = "8971820518";
List<String> lst = new List<String>();
for(int i=0;i<lines.Length;i++)
{
if (!lines[i].Equals(strRemove)) //if string is part of line use Contains()
{
lst.Add(lines[i]);
}
}
File.WriteAllLines(path,lst.ToArray());
Solution 2: if you want to remove the Line based on user input LineNO (matched with exact line no in file) you can try this
string path = #"C:\Data.txt";
string[] lines = File.ReadAllLines(path);
int iRemoveLineNo = 6;
List<String> lst = new List<String>();
for(int i=0;i<lines.Length;i++)
{
if (iRemoveLineNo-1!=i)
{
lst.Add(lines[i]);
}
}
File.WriteAllLines(path,lst.ToArray());
I am trying to add items to a listView from an array of strings using indexes.
Following is my code:
using (StringReader tr = new StringReader(Mystring))
{
string Line;
while ((Line = tr.ReadLine()) != null)
{
string[] temp = Line.Split(' ');
listview1.Items.Add(new ListViewItem(temp[1], temp[3]));
}
}
But it gives an index out of bound error.
When I do not use index as
listview1.Items.Add(new ListViewItem(temp));
it works fine and adds the contents of the array to the listView.
And it also adds zero index string to the listView. For one, two or other indexes it gives the same error.
Please any one tell me how I can add only my required strings to listView using index or any other method.
Thanks in advance!
If the string ends with a line break, you will get an empty string as the last line. Skip any empty lines:
using (StringReader tr = new StringReader(Mystring)) {
string Line;
while ((Line = tr.ReadLine()) != null) {
if (Line.Length > 0) {
string[] temp = Line.Split(' ');
listview1.Items.Add(new ListViewItem(temp[1], temp[3]));
}
}
}
Additionaly, you could check the length of the array after splitting, but I assume that if there is anything at all in the line, it would be correct.
I'm trying to read a text file which contains numbers separated by a comma. When I read using File.Readline() I get it to a string[]. I need to convert it in to a int array but it gives an error.
The contents of the text file:
146429,143689,144380,141523,139572,136930,133714,130011,125843,121110,115974,110363,104367,97909,91245,84218,77008,69626,62058,54445,46942,39436,32146,24932,18359,12601,9039,9776,13638,18314,23221,27728,32142,35941,39577,42657,45692,48180
My code:
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split(new string[] { " , " }, StringSplitOptions.None);
for (int i = 0; i < values.Length; i++)
{
// Console.WriteLine(values[i]);
valArr[LineCount][i] = Convert.ToInt64(values[i]); // error
}
LineCount++;
}
I think this is what you are after:
static void Main(string[] args)
{
var sr = new StreamReader(#"d:\test.txt");
long[] data = ExtractData(sr).ToArray();
}
private static IEnumerable<long> ExtractData(StreamReader sr)
{
string line;
while ((line = sr.ReadLine()) != null)
{
var items = line.Split(',');
foreach (var item in items)
{
yield return Convert.ToInt64(item);
}
}
}
With my test file (d:\test.txt) holding:
1,2,3,4,5
1,2,3,4
I get the array containing:
1,2,3,4,5,1,2,3,4
EDIT
As Monroe pointed out, I missed the fact you wanted an array of arrays. Here's another version that gives such a jagged array. Still keeping yield in though ;)
static void Main(string[] args)
{
var sr = new StreamReader(#"d:\test.txt");
var data = ExtractData(sr).ToArray();
}
private static IEnumerable<long[]> ExtractData(StreamReader sr)
{
string line;
while ((line = sr.ReadLine()) != null)
{
yield return line.Split(',').Select(i => Convert.ToInt64(i)).ToArray();
}
}
Using List can help you, and use StringSplitOptions.RemoveEmptyEntries to prevent null exception in Convert.ToInt64
var lineArray = new List<List<Int64>>();
foreach (var lineString in File.ReadAllLines("path"))
{
var line = new List<Int64>();
string[] values = lineString.Split(new[] { ',', ' ' },
StringSplitOptions.RemoveEmptyEntries);
line.AddRange(values.Select(t => Convert.ToInt64(t)));
lineArray.Add(line);
}
and using it:
// Array of numbers for specific line
var resultArray = lineArray[lineNumber].ToArray();
It should be something nearly to:
int yourIntArray =
new List<string>(RealAllText(fileName)
.Split(new char[] {',', '\r', '\n', ' '},
stringSplitOptions.RemoveEmptyEntries))
.ConvertAll<int>(s => int.Parse(s))
.ToArray();
Of course, for more robustness, int.Parse should be replaced with some method that will handle errors in numbers, and so on...
EDIT:
Oh, I just saw that you have lines that are another index to your array... Well then, this code should be modified in that case, but I'll leave that to you.
I think this is what you want to do. Only thing is that your vallArr should be a two dimensional array that can keep all values. Something like var valArr = new Int64[x, y];
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split(new string[] { " , " }, StringSplitOptions.None);
for (int i = 0; i < values.Length; i++)
{
valArr[LineCount, i] = Int64.Parse(values[i]);
}
LineCount++;
}