如何从文本文件中逐行读取? [英] How to read from a text file line by line?
本文介绍了如何从文本文件中逐行读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好,我需要阅读一个文本文件.
文本文件中只有2行.而且我需要以字符串形式逐行读取两者.阅读后,我想使用它(连接).
例如,每一行都表示为string1和string2.我将串联一个这样的句子
您的电话号码是"+ string1 +",而您的端口是"+ string2".
我的问题是,我该怎么做?我读为数组?并将其转换为字符串?或反之亦然?
我真的很困惑.
预先感谢.
Hello, I need to read from a text file.
There are only 2 lines in the text file. And I need to read both, line by line as a string. After reading it, I want to use it (concatenate).
For example, each line is represented as string1 and string2. I will concatenate to make a sentence like
"Your number is " + string1 + " and your port is " + string2".
My question is, how do I do it? I read it as array? And convert it to string? Or vice versa?
I''m really confused.
Thanks in advance.
推荐答案
public static string MyMethod(string filename)
{
string result = string.Empty;
try
{
string[] lines = File.ReadAllLines(filename);
result = "Your number is " + lines[0] + " and your port is " + lines[1] + ".";
}
catch (FileNotFoundException e)
{
// Deal with it!
}
catch (IndexOutOfRangeException e)
{
// Deal with it too! (there aren't two lines in the file)
}
// Catch other possible Exceptions here!
return result;
}
在下面的示例中使用Stringbuilder ...全部
C#逐行读取文本文件 [
Use Stringbuilder with below example...that''s all
C# Read Text File Line-by-Line[^]
Stringbuilder sample code
StringBuilder sb = new StringBuilder();
int count = lines1.Length;
for (int i = 0; i < count; i++)
{
string line = lines1[i];
sb.AppendLine(line);
}
Console.WriteLine(sb.ToString());
这篇关于如何从文本文件中逐行读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文