2013-09-24 72 views
0

這是我打開文件代碼:如何知道如果我打開的文件是一個文本文件或沒有在VB.net

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 

我的問題是我怎麼能知道,如果文件我打開的是.txt文件還是不是?可能嗎?謝謝。

回答

1

我的問題是如何知道我打開的文件是否是.txt文件?可能嗎?謝謝。

用戶挑選後,您可以查看文件的擴展名:

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

非常感謝您,先生:) – Matthew

相關問題