如何正确取得文件的真正类型
vb.net中,要求用户提供的是.xls格式,可是当把不是该格式的文件改后也行,现在问题是我应该如何正确取得该文件的真正格式类型,在校验中将此问题查处,谢谢!
--------------------编程问答--------------------
二进制方式读取文件的前几个字节,看是不是xls的文件,不过这样太麻烦,还是你在用的时候try一下,出现异常就异常处理
--------------------编程问答--------------------
这种方法我试过,好不稳定,多个.txt文件,进行读取前两个字节时候,发现他们之间有时候一样,另外一个问题是.doc,.xls文件,他们的前几个字节一样,现在对这种方法已经失去信心,还望高手指点!
--------------------编程问答--------------------
将就一下:
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Console.WriteLine(Excel.IsValid("g:\test.xls"))
Console.WriteLine(Excel.IsValid("g:\test.xls.ddd"))
Console.WriteLine(Excel.IsValid("g:\notexists.xls"))
Console.WriteLine(Excel.IsValid("g:\data.xml"))
End Sub
End Class
Public Class Excel
Private Const ConnnectionStringFormat As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0"";"
Public Shared Function IsValid(ByVal file As String) As Boolean
If Not System.IO.File.Exists(file) Then Return False
Using cn As New OleDb.OleDbConnection(String.Format(ConnnectionStringFormat, file))
Try
cn.Open()
Return True
Catch ex As Exception
Return False
End Try
End Using
End Function
End Class
--------------------编程问答--------------------
呵呵 够狠,我再去试试
--------------------编程问答--------------------
经过测试,不正确啊,明明是将test.doc--->test.xls 而返回值还是true
--------------------编程问答--------------------
是么?
--------------------编程问答--------------------
我的是False
--------------------编程问答--------------------
如果这样,你的还是True,我就没办法了:
Public Class Excel
Private Const ConnnectionStringFormat As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=""Excel 8.0"";"
Public Shared Function IsValid(ByVal file As String) As Boolean
If Not System.IO.File.Exists(file) Then Return False
Using cn As New OleDb.OleDbConnection(String.Format(ConnnectionStringFormat, file))
Try
cn.Open()
Dim table As DataTable = cn.GetSchema("Tables")
If table.Rows.Count > 0 Then
If table.Rows(0).Item("TABLE_NAME").ToString.EndsWith("$") Then
cn.Close()
Return True
End If
End If
cn.Close()
Return False
Catch ex As Exception
Return False
End Try
End Using
End Function
End Class
补充:.NET技术 , VB.NET