Professional Documents
Culture Documents
It uses OpenFileDialog to browse text files and once text file is selected, it is loaded in a FlowDocumentReader that allows you to view, paging, and find options. First, let's create a UI with a TextBox, a Button, and a FlowDocumentViewer control. The UI looks like Figure 1.
On Button control, we will browse a text file and set TextBox.Text property to the selected file. As you can see from code below, we create a Paragraph and add the selected text file using Paragraph.Inlines.Add method. After that, we create a FlowDocument by passing this Paragraph and in the end; we set FlowDocumentReader.Document property to the FlowDocument. Code sample in C#:
private void button1_Click(object sender, RoutedEventArgs e) { // Create OpenFileDialog Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); // Set filter for file extension and default file extension dlg.DefaultExt = ".txt"; dlg.Filter = "Text documents (.txt)|*.txt"; // Display OpenFileDialog by calling ShowDialog method Nullable<bool> result = dlg.ShowDialog(); // Get the selected file name and display in a TextBox if (result == true) { // Open document string filename = dlg.FileName; FileNameTextBox.Text = filename; Paragraph paragraph = new Paragraph(); paragraph.Inlines.Add(System.IO.File.ReadAllText(filename)); FlowDocument document = new FlowDocument(paragraph); FlowDocReader.Document = document; } }
Dim document As FlowDocument = New FlowDocument(paragraph) FlowDocReader.Document = document End If End Sub
Now if you run the application and browse a text file, the output looks like Figure 2.
Figure 2
Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.