C#-流阅读器无法将文本从文件文本传递到文本框

try
{
    Form frmShow = new Form();
    TextBox txtShowAll = new TextBox();
    frmShow.StartPosition = FormStartPosition.CenterScreen;
    frmShow.Font = this.Font;
    frmShow.Size = this.Size;
    frmShow.Icon = this.Icon;
    frmShow.Text = "All data";
    txtShowAll.Dock = DockStyle.Fill;
    txtShowAll.Multiline = true;
    frmShow.Controls.Add(txtShowAll);
    frmShow.ShowDialog();

    StreamReader r = new StreamReader("empData.txt");
    string strShowAllData = r.ReadToEnd();                
    txtShowAll.Text = strShowAllData;
    r.Close();
}
catch (Exception x)
{
     MessageBox.Show(x.Message);
}

我确定文件名正确
当我运行程序时,它显示一个空的文本框.

结果
C#-流阅读器无法将文本从文件文本传递到文本框

解决方法:

我只是注意到您在对话框模式下显示表单后将文本添加到文本框中.您为什么不移动frmShow.ShowDialog();?就像我在下面的代码中所做的那样,一直到try块的末尾,并确保empData.txt位于其路径中.

        try
        {
            Form frmShow = new Form();
            TextBox txtShowAll = new TextBox();
            frmShow.StartPosition = FormStartPosition.CenterScreen;
            frmShow.Font = this.Font;
            frmShow.Size = this.Size;
            frmShow.Icon = this.Icon;
            frmShow.Text = "All data";
            txtShowAll.Dock = DockStyle.Fill;
            txtShowAll.Multiline = true;
            frmShow.Controls.Add(txtShowAll);

            StreamReader r = new StreamReader("empData.txt");
            string strShowAllData = r.ReadToEnd();
            txtShowAll.Text = strShowAllData;
            r.Close();

            frmShow.ShowDialog();
        }
        catch (Exception x)
        {
            MessageBox.Show(x.Message);
        }
上一篇:C# 的三种序列化方法


下一篇:c-从文件中删除字符