我有一个文本文件,它包含8000多行。我需要打印一个特定行,还需要打印另一行,即第一行的前一行。问题是第二行没有uniqe功能,因此我无法像调用第一行那样来调用它。
总结
:
-第二行
-第一行
:
如何使用第一行获得第二行?
我知道我应该反击并捕获第二行,但我不知道如何。感谢您的帮助。
答案 0 :(得分:1)
我创建了一个.txt文件,其中有一堆行,并埋在中间是两行,第一行为“ Frank”,第二行为“ Ball”。要打印“ Frank Ball”,请尝试以下操作:
string line;
string line1;
string line2;
System.IO.StreamReader file = new System.IO.StreamReader(@"c:\test.txt");
//walk the file line by line
while ((line = file.ReadLine()) != null)
{
if(line.Contains("Ball"))
{
//Once you find your search value, set line2 to the line and stop walking the file.
line2 = line;
break;
}
//set line1 to the line value to hold onto it if you find your search value
line1 = line;
}
//Now you have both strings and you can concatenate them however you want and print them
string s = line1 + " " + line2;
PrintDocument p = new PrintDocument();
p.PrintPage += delegate (object sender1, PrintPageEventArgs e1)
{
e1.Graphics.DrawString(s, new Font("Times New Roman", 12), new SolidBrush(Color.Black), new RectangleF(0, 0, p.DefaultPageSettings.PrintableArea.Width, p.DefaultPageSettings.PrintableArea.Height));
};
try
{
p.Print();
}
catch (Exception ex)
{
throw new Exception("Exception Occured While Printing", ex);
}
file.Close();
答案 1 :(得分:0)
int
我们阅读每一行并将其保存到static string GetPreviousLine(string[] lines)
{
string temp = "";
foreach (string line in lines)
{
if (line == "First Line") return temp;
else temp = line;
}
throw new Exception("not found");
}
。然后,我们读取下一行,如果它是temp
,我们知道line 1
是temp
,否则我们将新行保存到line 2
并以相同的方式继续。
答案 2 :(得分:0)
我知道我应该反击并捕获第二行,但是我不知道如何。
要计算行数,您可以简单地在方法for
返回的lines
数组上使用System.IO.File.ReadAllLines(filePath)
循环。这将在每次迭代中递增,并且您可以使用lines[i - 1]
访问上一行。
这是一种方法,该方法将使用for
循环搜索字符串数组,查找与特定字符串匹配的行(在本示例中为不区分大小写),如果搜索项为,则返回前一个数组项找到:
private static string GetLineBefore(string lineToFind, string[] lines)
{
// Argument validation to avoid NullReferenceException or unnecessary search
if (lines != null && !string.IsNullOrEmpty(lineToFind))
{
// Start at the second line (index 1) since there is no line before the first
for (int i = 1; i < lines.Length; i++)
{
if (lines[i].Equals(lineToFind, StringComparison.OrdinalIgnoreCase))
{
// Since 'i' represents the index of the first line that we were
// searching for, we return the previous item, at index 'i - 1'
return lines[i - 1];
}
}
}
// If we never found our first line, return null to indicate no results
return null;
}
您可以这样称呼它:
var filePath = @"f:\public\temp\temp.txt";
var searchLine = "This is the text for the first line that I want to find";
// This will represent the line before the first one above
var previousLine = GetLineBefore(searchLine, File.ReadAllLines(filePath));