如何处理代码中的外部异常
本文关键字:外部 异常 代码 何处理 处理 | 更新日期: 2023-09-27 18:34:15
我正在尝试以计时器的数量捕获图像并自动保存它,我已经尝试了代码 但是当我运行此代码时,会抛出外部异常。如果我尝试捕获异常,代码会运行,但它既不会将捕获的图像保存在提到的路径中,也不会保存在其他任何地方。这里 picCap 是我的图片框的名称
我的代码是,
WebCam webcam;
int duration = 0;
private void timer1_Tick(object sender, EventArgs e)
{
duration++;
textBox1.Text = duration.ToString();
bool ischecked = radioButton2.Checked;
if (duration <= 3)
{
radioButton2.Checked = true;
if (radioButton2.Checked == true)
{
picCap.Image.Save(@"C:'Users'Administrator'Desktop", ImageFormat.Jpeg);
//External Exception not handled
}
else
{
webcam.Stop();
timer1.Stop();
}
}
else
{
radioButton2.Checked = false;
// radioButton3.Visible = false;
radioButton3.Checked = true;
}
}
//start
private void button1_Click(object sender, EventArgs e)
{
timer1.Enabled = true;
timer1.Start();
webcam.Start();
}
//stop
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
webcam.Stop();
}
private void mainWinForm_Load(object sender, EventArgs e)
{
webcam = new WebCam();
webcam.InitializeWebCam(ref picCap);
}
有关异常的其他详细信息
System.Runtime.InteropServices.ExternalException was unhandled by user code
HResult=-2147467259
Message=A generic error occurred in GDI+.
Source=System.Drawing
ErrorCode=-2147467259
StackTrace:
at System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
at System.Drawing.Image.Save(String filename, ImageFormat format)
at WindowsFormsApplication3.mainWinForm.timer1_Tick(Object sender, EventArgs e) in C:'Users'Administrator'documents'visual studio 2010'Projects'WindowsFormsApplication3'WindowsFormsApplication3'Form1.cs:line 37
at System.Windows.Forms.Timer.OnTick(EventArgs e)
at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message& m)
at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
at System.Windows.Forms.Application.DoEvents()
at WebCam_Capture.WebCamCapture.timer1_Tick(Object sender, EventArgs e)
InnerException:
异常指示该方法需要文件名而不是文件夹路径:
System.Drawing.Image.Save(String filename, ImageCodecInfo encoder, EncoderParameters encoderParams)
它可能会失败,因为它无法在没有文件名的情况下保存文件,因此请尝试添加一个类似于以下示例的文件:
picCap.Image.Save(@"C:'Users'Administrator'Desktop'MyFilename.jpeg", ImageFormat.Jpeg);