在VB.NET中检查文件类型? [英] Filetype check in VB.NET?

查看:150
本文介绍了在VB.NET中检查文件类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图像大小调整的程序,它的工作原理。问题是当用户在文件选择对话框中选择非图像文件时,它会崩溃。如何检查图像文件?

I have an image resized program and it works. The problem is when a user selects a non-image file in the file select dialog, it crashes. How can I check for image files?

推荐答案

这是VB.NET等效的 0xA3的回答,因为OP坚持使用VB版本。

Here's the VB.NET equivalent of 0xA3's answer since the OP insisted on a VB version.

Function IsValidImage(filename As String) As Boolean
    Try
        Dim img As System.Drawing.Image = System.Drawing.Image.FromFile(filename)
    Catch generatedExceptionName As OutOfMemoryException
        ' Image.FromFile throws an OutOfMemoryException  
        ' if the file does not have a valid image format or 
        ' GDI+ does not support the pixel format of the file. 
        ' 
        Return False
    End Try
    Return True
End Function

您可按如下方式使用它:

You use it as follows:

If IsValidImage("c:\path\to\your\file.ext") Then
    'do something
    '
Else
    'do something else
    '
End If






编辑:

我不建议您检查文件扩展名。任何人都可以使用 .jpg 扩展程序保存不同的文件(例如文本文档)并诱骗您使应用程序获得它是一个图像。



I don't recommend you check file extensions. Anyone can save a different file (text document for instance) with a .jpg extension and trick you app into beleiving it is an image.

最好的方法是使用上面的函数加载图像或打开前几个字节并检查JPEG签名。

The best way is to load the image using the function above or to open the first few bytes and check for the JPEG signature.




您可以在此处找到有关JPEG文件及其标题的更多信息:



You can find more information about JPEG files and their headers here:

  • http://www.fastgraph.com/help/jpeg_header_format.html
  • http://en.wikipedia.org/wiki/JPEG

这篇关于在VB.NET中检查文件类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆