WPF VB.Net Save File Dialog
The Idea
Saving content to a txt file
- A button on a XAML File
- Upon clicked, open a save file dialog
- Choose a file or create new file
- File created if not exists, data written to file
The Chunks
-
We’re going to create a SaveFileDialog class from .Net to open a save file dialog
' Create an instance of the open file dialog box. Dim exportFileDialog As New SaveFileDialog
-
Only
.txt
files allowed, we’re putting a restriction by usingfilter
' Set filter options and filter index. exportFileDialog.Filter = "Text Files (*.txt)|*.txt"
-
Set the ‘open file’ window title and show it to user
exportFileDialog.Title = "Save as Text file" exportFileDialog.ShowDialog()
-
Check if user input valid file name
If exportFileDialog.FileName <> “” Then
-
Get filename from user input
Dim selectedfile As String = exportFileDialog.FileName
-
Check if file exists, if not, create file
If System.IO.File.Exists(selectedfile) <> True Then System.IO.File.Create(selectedfile).Dispose() End If
-
We’re using
StreamWriter
to write to file, don’t forget to close the stream after useDim objWriter As New System.IO.StreamWriter(selectedfile) objWriter.Write(“Writing to file!!”) objWriter.Close()
The Final Function Code
Private Function SaveToTextFile() As Boolean
' Create an instance of the open file dialog box.
Dim exportFileDialog As New SaveFileDialog
' Set filter options and filter index.
exportFileDialog.Filter = "Text Files (*.txt)|*.txt"
exportFileDialog.Title = "Save as Text file"
exportFileDialog.ShowDialog()
' Call the ShowDialog method to show the dialogbox.
If exportFileDialog.FileName <> "" Then
Dim selectedfile As String = exportFileDialog.FileName
If System.IO.File.Exists(selectedfile) <> True Then
System.IO.File.Create(selectedfile).Dispose()
End If
Dim objWriter As New System.IO.StreamWriter(selectedfile)
objWriter.Write("Writing to file!!")
objWriter.Close()
MsgBox("Text written to file")
End If
Return True
End Function
blog comments powered by Disqus