3 回答
TA贡献1853条经验 获得超9个赞
我用一堆行创建了一个 .txt 文件,中间埋了两行,第一行是“弗兰克”,第二行是“球”。要打印“弗兰克球”试试这个:
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();
TA贡献1856条经验 获得超5个赞
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,否则我们将新行保存到temp并以相同的方式继续。
TA贡献1886条经验 获得超2个赞
我知道我应该反制线条并捕获第二行,但我不知道如何。
要计算行数,您可以简单地对方法返回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));
- 3 回答
- 0 关注
- 233 浏览
添加回答
举报