WPF OpenFileDialog to read in a text file using VB.NET
In this article, we will see how to use a WPF OpenFileDialog to read in a text file.
In this article, we will see how to use a WPF OpenFileDialog to read in a text file.
The OpenFileDialog is used to browse files on a machine. The OpenFileDialog class defined in Microsoft.Win32.OpenFileDialog namespace represents an OpenFileDialog control in WPF. We will use StackPanel and ScrollViewer in this example. This example shows how you can allow the user to click on a button and choose a text file to view the contents of the file in a scrollable box on the screen.
Example:- This code of .axml
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<StackPanel Margin="10" HorizontalAlignment="Left">
<StackPanel HorizontalAlignment="Left">
<Button Content="Load File" Width="100" Background="Silver"
Height="40" FontSize="20"
Margin="0 0 0 10" Click="Button_Click" />
</StackPanel>
<ScrollViewer Width="300" Height="200" Cursor="ScrollAll">
<Border Background="Plum"
CornerRadius="5"
BorderBrush="Red"
BorderThickness="2" Cursor="SizeAll">
<TextBox x:Name="TextFileContent"
TextWrapping="Wrap" Background="AliceBlue"/>
</Border>
</ScrollViewer>
</StackPanel>
</Grid>
</Window>
This code of .vb
Imports Microsoft.Win32
Imports System.IO
---------------------------------------------------------------------------------
Class Window1
Private Sub Button_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim dlg As New OpenFileDialog()
dlg.DefaultExt = ".txt"
dlg.InitialDirectory = "C:test"
dlg.Filter = "Text documents (.txt)|*.txt"
Dim result As System.Nullable(Of Boolean) = dlg.ShowDialog()
If result = True Then
TextFileContent.Text = File.ReadAllText(dlg.FileName)
End If
End Sub
End Class
---------------------------------------------------------------------------------
Output:-
I hope this code help you.