New to Telerik UI for WinFormsStart a free 30-day trial

How to Save Document in SyntaxEditor

Updated over 6 months ago

Environment

Product VersionProductAuthor
2020.1.218RadSyntaxEditor for WinFormsDesislava Yordanova

Description

RadSyntaxEditor is purposed to provide editing options for a document loaded in the control. A common requirement is to save the changes that have been made to the document.

Solution

This solution demonstrates how to get very easily the document's content by using the selection functionality and write the content to a file:

C#

public RadForm1()
{
    InitializeComponent();
    using (StreamReader Reader = new StreamReader(@"..\..\Sample.cs"))
    {
        this.radSyntaxEditor1.Document = new TextDocument(Reader);
    }
}

private void radButton1_Click(object sender, EventArgs e)
{
    this.radSyntaxEditor1.SelectAll();
    string selectedText = this.radSyntaxEditor1.SyntaxEditorElement.Selection.GetSelectedText();
    string fileName = @"..\..\FILENAME.txt";
    if (!File.Exists(fileName))
    {
        File.Create(fileName).Close();
        using (StreamWriter sw = File.AppendText(fileName))
        {
            sw.WriteLine(selectedText);
        }
    }
    else
    {
        File.WriteAllText(fileName, string.Empty);
        using (StreamWriter sw = File.AppendText(fileName))
        {
            sw.WriteLine(selectedText);
        }
    }
}
    

See Also