簡體   English   中英

如何在C#中讀取文本文件中的多行?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM