.net 如何检查文件是否为C++;?
在使用之前,我想检查硬盘中的文件是否是图像 我正在使用C++/Cli.net 如何检查文件是否为C++;?,.net,winforms,visual-studio-2008,visual-c++,c++-cli,.net,Winforms,Visual Studio 2008,Visual C++,C++ Cli,在使用之前,我想检查硬盘中的文件是否是图像 我正在使用C++/Cli OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog; if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ) { Bitmap^ PreviewImage = gcnew Bitmap(openFileDialog1->FileName); /
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ) {
Bitmap^ PreviewImage = gcnew Bitmap(openFileDialog1->FileName); //If File is not an image this will crash.
}
正如我在这行中所评论的,如果文件不是一个会产生错误的图像,我如何检查文件是否是一个图像
提前感谢。捕获异常 .Net没有任何
TryRead
方法返回false而不是引发异常
您可以检查扩展名,但.png
文件也可能是无效图像。(但是,您应该设置
过滤器
,以阻止用户首先选择其他文件类型)惯例通常规定文件内容由扩展名描述。如果我是你,我会做一些基本的检查,以确保你只允许.bmp、.jpeg、.jpg、.gif等。另外,正如另一个答案所提到的,你应该确保捕获异常,并且你可以告诉用户那里发生了错误
您可以这样做:
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
if ( openFileDialog1->ShowDialog() == System::Windows::Forms::DialogResult::OK ) {
try
{
Bitmap^ PreviewImage = gcnew Bitmap(openFileDialog1->FileName); //If File is not an image this will crash.
}
catch(Exception ^ex)
{
//do something with the exception here
}
}
我会在OpenFileDialog中添加一个过滤器,这样用户只能选择图像
OpenFileDialog^ openFileDialog1 = gcnew OpenFileDialog;
openFileDialog1->Filter = "Image Files(*.BMP;*.JPG;*.GIF)|*.BMP;*.JPG;*.GIF" ;
看
但是,在尝试打开文件时仍然需要检查错误,因为用户总是可以尝试在对话框的文本框中键入无效的文件名
今天的编程是一场软件工程师之间的竞赛
建立更大更好的防白痴程序,整个宇宙都在努力
为了培养更大更好的白痴。到目前为止,宇宙正在获胜
有钱的厨师
您介意展示一个捕获此异常的示例吗?非常感谢。你是在问如何使用
catch
block吗?哈哈,哦,是的,我很糟糕,我还想到了别的事情;D我很清楚。谢谢@我发现他仍然需要检查错误。我编辑了答案以反映这一点