Loading and Saving Files
AvaloniaEdit provides helper methods to load and save text files while automatically handling stream management and encoding detection.
Loading
Use the Load method on the TextEditor.
// Load from a file path
textEditor.Load("path/to/file.cs");
// Load from a stream
using (var stream = File.OpenRead("path/to/file.cs"))
{
textEditor.Load(stream);
}
This will automatically populate the Document property.
Saving
Use the Save method.
// Save to a file path
textEditor.Save("path/to/file.cs");
// Save to a stream
using (var stream = File.Create("path/to/file.cs"))
{
textEditor.Save(stream);
}
Direct Document Manipulation
If you aren't using the TextEditor control directly (e.g., headless testing), you can use TextDocument methods:
var doc = new TextDocument();
doc.Text = "Initial content";
// Write to a TextWriter
using (var writer = new StreamWriter("output.txt"))
{
doc.WriteTextTo(writer);
}