[英]how to read multi lines in text file in c#?
我喜欢阅读检查文本是否具有多行或单行,然后我要阅读该多行并将其转换成单行,我该怎么做?
您真的不需要检查,因为File.ReadAllLines()
总是返回一个字符串数组,而不管行数如何。 您可以利用这种行为,只需将返回的数组与选择的分隔符连接起来即可。
string singleLine = string.Join(" ", File.ReadAllLines("filepath"));
string text = String.Empty;
if(textbox.Text.Contains(Environment.NewLine))
{
//textbox contains a new line, replace new lines with spaces
text = textbox.Text.Replace(Environment.NewLine, " ");
}
else
{
//single line - simply assign to variable
text = textbox.Text;
}
尝试类似的事情(取决于您如何对待“线条”):
System.IO.File.ReadAllText(path).Replace("\n\r", "");
这将从文本文件中读取所有行,并使用;将它们连接为一个字符串。 作为分隔符:
string[] lines = File.ReadAllLines("myfile.txt");
string myLine = String.Join(";", lines);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.