skip lines that contain semi-colon in text file
How can I skip lines in a text file that contain a semi-colon at the beginning of a line? I'm currently reading a text file in with server na开发者_如何学Cmes which works fine. I want to throw a semi-colon at the beginning of a line to comment it out in case a server is going into maintenance mode.
var lines = File.ReadAllLines( path );
foreach( var line in lines )
{
if( line.StartsWith( ";" ) )
{
continue;
}
else
{
// do your stuff
}
}
EDIT: OK, so we can make this easier...
foreach (var currentLine in File.ReadAllLines(@"C:\somefile.txt"))
{
if (currentLine.StartsWith(";")) continue;
// Pretend this is the function you want to do below.
ProcessLine(currentLine);
}
if (!textline.StartsWith(";"))
// do something
Assuming your using something that derives from System.IO.TextReader you could Peek
at the next character and see if it's a semicolon. Otherwise read the line and check the first character of the string.
Try this:
var allLines = System.IO.File.ReadAllLines("SOME-PATH");
var filteredLines = from l in allLines
where !l.StartsWith(";")
select l;
I understand you are asking this question for C#.
In this case you can use a startswith from string class, i am not sure how is your code but i think this can help you:
using System;
using System.IO;
class Program {
static void Main( string[] args ) {
string filePath = @"test.txt";
string line;
string fileContent = "";
if (File.Exists( filePath )) {
StreamReader file = null;
try {
file = new StreamReader( filePath );
while ((line = file.ReadLine()) != null) {
if (!line.StartsWith(";")){
Console.WriteLine( line );
fileContent += line;
}
}
} finally {
if (file != null)
file.Close();
}
}
}
}
}
foreach(string line in readLines())
{
if (line[0] == ';') continue;
...
}
Maybe StartWith
will help
string line = null;
using (System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt"))
{
while ((line = file.ReadLine()) != null)
{
if (!line.StartsWith(";"))
{
// do thomething
}
}
}
in .NET 4.0:
File.ReadLines("c:\test.txt").Where(x => !x.StartsWith(";"));
Maybe you want AsParallel
File.ReadLines("c:\test.txt").AsParallel().Where(x => !x.StartsWith(";"));
;)
精彩评论