C#从文件或标准输入设备读取指定行的方法
本文实例讲述了C#从文件或标准输入设备读取指定行的方法。分享给大家供大家参考。具体如下:
usingSystem;
usingSystem.IO;
usingSystem.Runtime.InteropServices;
usingSystem.Text.RegularExpressions;
usingSystem.Collections.Generic;
namespaceRobvanderWoude
{
classReadLine
{
staticintMain(string[]args)
{
#regionCommandLineParsing
stringfilename=string.Empty;
intlinestart=1;
intlineend=2;
boolconcat=false;
booladdspaces=false;
stringconcatchar=string.Empty;
boolskipempty=false;
booltrimlines=false;
boolnumlines=false;
boolredirected;
boolset_c=false;
boolset_l=false;
boolset_s=false;
boolset_t=false;
boolset_input=false;
if(ConsoleEx.InputRedirected)
{
set_input=true;
redirected=true;
}
else
{
if(args.Length==0)
{
returnWriteError();
}
redirected=false;
}
foreach(stringarginargs)
{
if(arg[0]=='/')
{
try
{
switch(arg.ToUpper()[1])
{
case'?':
returnWriteError();
case'C':
if(arg.ToUpper()!="/C"&&arg.ToUpper()!="/CS")
{
returnWriteError("Invalidcommandlineswitch"+arg);
}
concat=true;
if(arg.ToUpper()=="/CS")
{
addspaces=true;
}
if(set_c)
{
returnWriteError("Duplicatecommandlineargument/C*");
}
set_c=true;
break;
case'L':
if(arg.ToUpper().StartsWith("/L:")&&arg.Length>3)
{
if(arg[2]==':')
{
stringlinessel=arg.Substring(3);
stringpattern=@"^(\-?\d+)$";
Matchmatch=Regex.Match(linessel,pattern);
if(match.Success)
{
linestart=Convert.ToInt32(match.Groups[1].Value);
lineend=linestart+1;
}
else
{
pattern=@"^(\-?\d+)\.\.(\-?\d+)$";
match=Regex.Match(linessel,pattern);
if(match.Success)
{
linestart=Convert.ToInt32(match.Groups[1].Value);
lineend=Convert.ToInt32(match.Groups[2].Value)+1;
}
else
{
pattern=@"^(\-?\d+),(\-?\d+)$";
match=Regex.Match(linessel,pattern);
if(match.Success)
{
//numlinesistrueifthesecondnumber
//specifiesthenumberoflinesinsteadofalinenumber
numlines=true;
linestart=Convert.ToInt32(match.Groups[1].Value);
lineend=Convert.ToInt32(match.Groups[2].Value);
if(lineend<1)
{
returnWriteError("Invalidnumberoflines("+lineend.ToString()+"),mustbe1orhigher");
}
}
}
}
}
else
{
returnWriteError("Invalidcommandlineswitch"+arg);
}
}
else
{
returnWriteError("Invalidcommandlineswitch"+arg);
}
if(set_l)
{
returnWriteError("Duplicatecommandlineargument/L");
}
set_l=true;
break;
case'S':
if(arg.ToUpper()!="/SE")
{
returnWriteError("Invalidcommandlineswitch"+arg);
}
skipempty=true;
if(set_s)
{
returnWriteError("Duplicatecommandlineargument/SE");
}
set_s=true;
break;
case'T':
if(arg.ToUpper()!="/T")
{
returnWriteError("Invalidcommandlineswitch"+arg);
}
trimlines=true;
if(set_t)
{
returnWriteError("Duplicatecommandlineargument/T");
}
set_t=true;
break;
default:
returnWriteError("Invalidcommandlineswitch"+arg);
}
}
catch
{
returnWriteError("Invalidcommandlineswitch"+arg);
}
}
else
{
if(set_input)
{
returnWriteError("Multipleinputsspecified(file+redirectionormultiplefiles)");
}
if(redirected)
{
returnWriteError("Donotspecifyafilenamewhenusingredirectedinput");
}
else
{
filename=arg;
}
}
}
#endregion
try
{
intcount=0;
booloutput=false;
string[]lines;
List<string>alllines=newList<string>();
if(redirected)
{
//Readstandardinputandstorethelinesinalist
intpeek=0;
do
{
alllines.Add(Console.In.ReadLine());
}while(peek!=-1);
//Convertthelisttoanarray
lines=alllines.ToArray();
}
else
{
//Readthefileandstorethelinesinalist
lines=File.ReadAllLines(filename);
}
//Checkifnegativenumberswereused,andifso,
//calculatetheresultinglinenumbers
if(linestart<0)
{
linestart+=lines.Length+1;
}
if(lineend<0)
{
lineend+=lines.Length+1;
}
if(numlines)
{
lineend+=linestart;
}
//Iteratethroughthearrayoflinesanddisplay
//theonesmatchingthecommandlineswitches
foreach(stringlineinlines)
{
stringmyline=line;
if(trimlines)
{
myline=myline.Trim();
}
boolskip=skipempty&&(myline.Trim()==string.Empty);
if(!skip)
{
count+=1;
if(count>=linestart&&count<lineend)
{
if(concat)
{
Console.Write("{0}{1}",concatchar,myline);
}
else
{
Console.WriteLine(myline);
}
if(addspaces)
{
concatchar="";
}
}
}
}
}
catch(Exceptione)
{
returnWriteError(e.Message);
}
return0;
}
#regionRedirectionDetection
publicstaticclassConsoleEx
{
publicstaticboolOutputRedirected
{
get
{
returnFileType.Char!=GetFileType(GetStdHandle(StdHandle.Stdout));
}
}
publicstaticboolInputRedirected
{
get
{
returnFileType.Char!=GetFileType(GetStdHandle(StdHandle.Stdin));
}
}
publicstaticboolErrorRedirected
{
get
{
returnFileType.Char!=GetFileType(GetStdHandle(StdHandle.Stderr));
}
}
//P/Invoke:
privateenumFileType{Unknown,Disk,Char,Pipe};
privateenumStdHandle{Stdin=-10,Stdout=-11,Stderr=-12};
[DllImport("kernel32.dll")]
privatestaticexternFileTypeGetFileType(IntPtrhdl);
[DllImport("kernel32.dll")]
privatestaticexternIntPtrGetStdHandle(StdHandlestd);
}
#endregion
#regionErrorHandling
publicstaticintWriteError(Exceptione=null)
{
returnWriteError(e==null?null:e.Message);
}
publicstaticintWriteError(stringerrorMessage)
{
if(string.IsNullOrEmpty(errorMessage)==false)
{
Console.Error.WriteLine();
Console.ForegroundColor=ConsoleColor.Red;
Console.Error.Write("ERROR:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine(errorMessage);
Console.ResetColor();
}
Console.Error.WriteLine();
Console.Error.WriteLine("ReadLine,Version0.30beta");
Console.Error.WriteLine("Returnthespecifiedline(s)fromafileorStandardInput");
Console.Error.WriteLine();
Console.Error.Write("Usage:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("READLINEfilename[options]");
Console.ResetColor();
Console.Error.Write("or:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("READLINE[options]<filename");
Console.ResetColor();
Console.Error.Write("or:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("command|READLINE[options]");
Console.ResetColor();
Console.Error.WriteLine();
Console.Error.Write("Where:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("filename");
Console.ResetColor();
Console.Error.WriteLine("istheoptionalfiletoberead");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("command");
Console.ResetColor();
Console.Error.WriteLine("istheoptionalcommandwhoseoutputistoberead");
Console.Error.WriteLine();
Console.Error.Write("Options:");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/CC");
Console.ResetColor();
Console.Error.WriteLine("oncatenatelines");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/CSC");
Console.ResetColor();
Console.Error.Write("oncatenatelineswith");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("S");
Console.ResetColor();
Console.Error.WriteLine("pacesinbetween");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/L:n");
Console.ResetColor();
Console.Error.Write("readline");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("n");
Console.ResetColor();
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/L:n..m");
Console.ResetColor();
Console.Error.Write("readlines");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("n");
Console.ResetColor();
Console.Error.Write("through");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("m");
Console.Error.Write("/L:n,m");
Console.ResetColor();
Console.Error.Write("read");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("m");
Console.ResetColor();
Console.Error.Write("linesstartingatline");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.WriteLine("n");
Console.ResetColor();
Console.Error.WriteLine("(negativenumbersstartcountingfromtheendbackwards)");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/SES");
Console.ResetColor();
Console.Error.Write("kip");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("E");
Console.ResetColor();
Console.Error.WriteLine("mptylines");
Console.ForegroundColor=ConsoleColor.White;
Console.Error.Write("/TT");
Console.ResetColor();
Console.Error.WriteLine("rimleadingandtrailingwhitespacefromlines");
Console.Error.WriteLine();
Console.Error.WriteLine("Examples:");
Console.Error.WriteLine("READLINEfilereadthefirstnon-emptyline(default)");
Console.Error.WriteLine("READLINEfile/L:2/SEreadthesecondnon-emptylineoffile");
Console.Error.WriteLine("READLINEfile/L:5..7readlines5..7offile");
Console.Error.WriteLine("READLINEfile/L:-1readthelastlineoffile");
Console.Error.WriteLine("READLINEfile/L:-2..-1readthelast2linesoffile");
Console.Error.WriteLine("READLINEfile/L:-2,2readthelast2linesoffile");
Console.Error.WriteLine();
Console.Error.Write("CheckforredirectionbyHansPassanton");
Console.ForegroundColor=ConsoleColor.DarkGray;
Console.Error.WriteLine("StackOverflow.com");
Console.Error.WriteLine("/questions/3453220/how-to-detect-if-console-in-stdin-has-been-redirected");
Console.ResetColor();
Console.Error.WriteLine();
Console.Error.WriteLine("WrittenbyRobvanderWoude");
return1;
}
#endregion
}
}
希望本文所述对大家的C#程序设计有所帮助。