Knowledge Base > RichTextBox > Implementation Knowledge Base Home | Login
Search the Knowledge Base
 
Start Search in the Following Category

Reading and writing files to and from RTB

In order to write the contents of a file to a RichTextBox control or write the content of a RichTextBox control to a file, all you need is something like this:

<%@ Page Language="C#" AutoEventWireup="true" ValidateRequest="false" %>
<%@ Register TagPrefix="RTB" Namespace="RichTextBoxControl" Assembly="RichTextBox" %>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
    "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>ReadInFile</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" >
</head>
<body>

<form id="Form1" runat="server">
<rtb:richtextbox id="myRtb" runat="server"/><br/>
<asp:button id="save" onclick="save_Click" runat="server" text="Save"/>
</form>

</body>
</html>

<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
    System.IO.FileStream fs;
    System.IO.StreamReader sr = null;

    if (!Page.IsPostBack)
    {
        try
        {
            fs = System.IO.File.OpenRead(Server.MapPath("~/TestDocument.txt"));
            sr = new System.IO.StreamReader(fs);
            myRtb.Text = sr.ReadToEnd();
        }
        finally
        {
            if (sr != null)
                sr.Close();
        }
    }
}

private void save_Click(object sender, EventArgs e)
{
    System.IO.FileStream fs;
    System.IO.StreamWriter sw = null;

    try
    {
        fs = System.IO.File.Create(Server.MapPath("~/TestDocument.txt"));
        sw = new System.IO.StreamWriter(fs);
        sw.Write(myRtb.TextXhtml);
    }
    finally
    {
        if (sw != null)
            sw.Close();
    }
       
}
</script>




Did this page answer your question? If not, try the Forums or contact us.

Copyright Richer Components 2005. All rights reserved. No part of this article may be reproduced or transmitted in any form, by any means (electronic, photocopying, recording or otherwise) without the prior written permission of Richer Components. All brand names and product names used in this article are trade names, service marks, trademarks, or registered trademarks of their respective owners.


Knowledge Base Software - myKB.com