How to know if the file I'm opening is a .txt file or not in VB.net

∥☆過路亽.° 提交于 2020-01-17 06:41:31

问题


This is my code for opening files:

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
    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

My question is how can I know if the file that I am opening is .txt file or not? Is it possible? Thank you.


回答1:


My question is how can I know if the file that I am opening is .txt file or not? Is it possible? Thank you.

You can check the extension of the file after the user picks it:

If (Path.GetExtension(filename).ToLower() = ".txt") Then
     ' It's a .txt file
End If


来源:https://stackoverflow.com/questions/18971076/how-to-know-if-the-file-im-opening-is-a-txt-file-or-not-in-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!