Blue Theme Orange Theme Green Theme Red Theme
 
Team Foundation Server Hosting
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Team Foundation Server Hosting
Search :       Advanced Search »
Home » WPF » Loading a text file in a WPF FlowDocumentReader

Loading a text file in a WPF FlowDocumentReader

In this article, I demonstrate how to load a text file in a FlowDocumentReader available in WPF using C#.

Author Rank :
Page Views : 10518
Downloads : 187
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
LoadTextFileInFlowDocumentViewerSample.zip
 
 
DevExpress Free UI Controls
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


The attached project is a WPF application written in C# and XAML. 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.

 

fdrImg1.jpg
Figure 1

 

The XAML code for the UI looks like this.

 

<Window x:Class="LoadTextFileInFlowDocumentViewerSample.Window1"

        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

        Title="Window1" Height="290" Width="600">

    <Canvas>

        <TextBox Height="32" HorizontalAlignment="Left" Margin="6,10,0,0" Name="FileNameTextBox"

                 VerticalAlignment="Top" Width="393" />

        <Button Content="Browse" Height="32" HorizontalAlignment="Left" Margin="405,10,0,0"

                Name="button1" VerticalAlignment="Top" Width="88" Click="button1_Click" />

     

            <FlowDocumentReader Name="FlowDocReader" Background="LightBlue"

                                Canvas.Top="50" Canvas.Left="5" Width="560"

                                Height="210">

        </FlowDocumentReader>

    </Canvas>

</Window>  


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;

    }

}

 

Code sample in VB.NET:

 

Private Sub button1_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)

        'Create OpenFileDialog

        Dim dlg As Microsoft.Win32.OpenFileDialog = 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

        If (dlg.ShowDialog() = True) Then

 

            '; Open document

            Dim filename As String = dlg.FileName

            FileNameTextBox.Text = filename

 

            Dim paragraph As Paragraph = New Paragraph()

            paragraph.Inlines.Add(System.IO.File.ReadAllText(filename))

            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.

 

fdrImg2.jpg
Figure 2

 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Mahesh Chand
Mahesh is the founder of C# Corner and Mindcracker Network, an author of several .NET programming books and a Microsoft MVP for 6 consecutive years. In his day to day work, Mahesh is a Senior Software Consultant with over 14 years of IT industry experience building systems for Financial and Banking, Engineering & Architectural, Imaging, Construction, Biological & Pharmaceuticals, Healthcare and Education industries. His expertise is Windows Forms, ASP.NET, Silverlight, WPF, WCF, Visual Studio 2010, SQL Server, and Oracle.  If you are looking for a Sharepoint, Windows Forms, ASP.NET, WPF, Silverlight, C#, VB.NET, Oracle, and SQL Server Consultant in Philadelphia area or remote location, drop me a line at MAHESH [AT] C-SHARPCORNER [DOT] COM.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
display detail of selected file on file browser by Amit Kumar On September 8, 2009
i want to display the detail of selected file on file browser in window os format like vista and window7
it is working but not showing the detail

private void button1_Click(object sender, RoutedEventArgs e)

{

System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();

dlg.Title = "select file manuuaaly";

dlg.ShowDialog();

}



help out
amit

Reply | Email | Modify 
need help by Adeline On January 9, 2011
Hi, Can i know how to import textfile (tab delimited text file) into wpf application and from wpf how can i analysis it into a 3d chart? Hope to heard from you soon. thank you regards, Adeline
Reply | Email | Modify 
Nevron Chart
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.