0

我正在尝试将 txt 文件中的行读入数组并将其显示到文本框中。这是我的代码:

protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack != true)
    {
        blogPostTextBox.Text ="";
        string blogFilePath = Server.MapPath("~") + "/Blogs.txt";
        string[] blogMessageArray = File.ReadAllLines(blogFilePath);

        // this for loop code does not work..I think.. 
        for (int i = 0; i < blogMessageArray.Length; i++)
        {
            string[] fileLineArray = blogMessageArray[i].Split(' ');
            blogPostTextBox.Text = blogMessageArray[i] + System.Environment.New Line.ToString();
        }   
    }
}

我的文本文件包含几行,我试图将每一行拆分为数组,并使用 for 循环或 while 循环将所有行显示到文本框中。

4

4 回答 4

3

更新:

对于ASP.Net

var items =File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).Where(x=>!string.IsNullOrEmpty(x));
blogPostTextBox.Text=string.Join(Environment.NewLine, items)

作为旁注,最好Path.Combine在从多个字符串构建路径时使用

string blogFilePath = Path.Combine( Server.MapPath("~") , "Blogs.txt");

if (IsPostBack != true)有效,但你可以这样做

if (!IsPostBack)

Winform

如果文本框控件的 Multiline 属性设置为 true,则可以使用TextBoxBase.Lines Property

blogPostTextBox.Lines =File.ReadAllLines(blogFilePath);

如果您需要分割每一行并设置为文本框文本,那么

blogPostTextBox.Lines = File.ReadAllLines(blogFilePath).SelectMany(line => line.Split()).ToArray();
于 2013-10-14T10:35:02.957 回答
1

您必须TextMode="MultiLine"在您的TextBox(默认值为SingleLine)中设置,然后您可以使用 Linq 以这种方式构建文本:

var allLinesText = blogMessageArray
     .SelectMany(line => line.Split().Select(word => word.Trim()))
     .Where(word => !string.IsNullOrEmpty(word));
blogPostTextBox.Text = string.Join(Environment.NewLine, allLinesText);
于 2013-10-14T10:34:53.560 回答
0

您需要将每一行附加到文本框。您在上面所做的是用每一行覆盖文本框的内容。

string[] blogMessageArray = File.ReadAllLines("");
blogPostTextBox.Text = "";
foreach (string message in blogMessageArray)
{
    blogPostTextBox.Text += message + Environment.NewLine;
}

虽然不是读入所有行,然后写出所有行,但为什么不将所有文本写到文本框中呢?

blogPostTextBox.Text = File.ReadAllText();
于 2013-10-14T10:33:33.957 回答
0

尽管您可以循环执行此操作,但您确实不需要(或不想)

用内置的点网方法替换您的循环,这些方法实际上可以满足您的需要。

See String.Join()

public static string Join(
    string separator,
    params string[] value
)

这会将 blogMessageArray 的所有元素与您指定的分隔符结合起来(在您的情况下为“\n”,HTML 不需要“\r\n”)

然后只需将其分配给属性 blogPostTextBox.Tex

于 2013-10-14T10:34:27.593 回答