Load a txt file in a TextBox

Here is a very simple piece of C# code to load a text file in a TextBox. Typical use to display a disclaimer

[Update 1: added using statement for the StreamReader]

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        using (StreamReader StreamReader1 =
            new StreamReader(Server.MapPath("disclaimer.txt")))
        {
            txtDisclaimer.Text = StreamReader1.ReadToEnd();
            StreamReader1.Close();
        }
    }
}

[Update 2: use the new File.ReadAllText() wrapper for StreamReader, exact same thing, but 1 line of code instead of 3...]

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtDisclaimer.Text =
File.ReadAllText(Server.MapPath("disclaimer.txt")); } }

FYI here is the static ReadAllText method in Reflector:

Then you could add a CheckBox to enable a Postback Button (disabled by default):

<input id="cbAgree" type="checkbox" onclick="ManageBtnGoState();" />
<label for="cbAgree" style="font-weight:bold; color:Red;">
I Agree with the present statement</label>
<asp:Button ID="btnGo" runat="server" Text="Take Survey"
onclick="btnGo_Click" Enabled="false" />

And the Js function:

<script type="text/javascript">
function ManageBtnGoState()
{
    $get('<%= btnGo.ClientID %>').disabled = 'disabled';  
    if ( $get("cbAgree").checked == true )
    {    $get('<%= btnGo.ClientID %>').disabled = '';  }
}
</script>

Note that $get() is a function from the ASP.NET AJAX client framework. If you don't have it please use document.getElementById() instead.

 

Another solution

Load the txt file from Resource.

First add the text file as Resource in a resx file of your project (here common.resx):

 

You can event have one file per language!


Then the code looks like:

protected void Page_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)
    {
        txtDisclaimer.Text = Resources.Common.disclaimer_en;
    }
}

You could add a check for the current culture and load the corresponding disclaimer file.

2 Comments

  • Since StreamReader implements IDisposable, it couldn't be bad to use using statement in your server code.

  • I like File.ReadAllText(path) instead of having to deal with StreamReaders. For example:

    txtDisclaimer.Text = File.ReadAllText(Server.MapPath("disclaimer.txt"));

Comments have been disabled for this content.