In my previous question: How to know if the file I'm opening is a .txt file or not in VB.net
I ask here how to know if I'm opening .txt file or not.
The code below is my code for opening a .txt file and prompt the user if the file is .txt of not.
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Dim ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
ofd1.FilterIndex = 2
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
'if the file is not .txt file
If (Path.GetExtension(filename).ToLower() <> ".txt") Then
MessageBox.Show("Please select text Files only", _
"RMI", _
MessageBoxButtons.OK, _
MessageBoxIcon.Warning)
'show the open file dialog
ofd1.ShowDialog()
'if the file is .txt file
Else
filename = ofd1.FileName
End If
'if the filename is existing
If System.IO.File.Exists(filename) = True Then
Dim objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End If
If the file that I selected is not .txt file, here is the output:
If I open a file that is not existing, here is the output:
In the 1st image, it only show the error message box, but in the 2nd image, the error message box is within the open file dialog.
My question is how can I show the error message box of the 1st image with the open file dialog?
Thank you.
Notes:
.txt
files only "txt files (*.txt)|*.txt"
OpenFileDialiog.CheckFileExists
and OpenFileDialiog.CheckPathExists
properties to prevent user to enter an invalid file name/path (display an error message)CheckFileExists
/ CheckPathExists
ShowDialog()
method. StreamReader
Dim filename As String = String.Empty
Dim TextLine As String = ""
Dim SplitLine() As String
Using ofd1 As New OpenFileDialog()
ofd1.Filter = "txt files (*.txt)|*.txt"
ofd1.FilterIndex = 2
ofd1.CheckPathExists = True
ofd1.CheckPathExists = True
ofd1.RestoreDirectory = True
ofd1.Title = "Open Text File"
'get the filename of the txt file
If ofd1.ShowDialog() = DialogResult.OK Then
filename = ofd1.FileName
Using objReader As New System.IO.StreamReader(filename)
'read the text file and populate the datagridview
Do While objReader.Peek() <> -1
TextLine = objReader.ReadLine()
TextLine = TextLine.Replace(" ", "")
SplitLine = Split(TextLine, ",")
dvList.Rows.Add(SplitLine)
Loop
End Using
End If
End Using