带有文本框的参数异常
本文关键字:参数 异常 文本 | 更新日期: 2023-09-27 18:36:57
我有一个文本框。当我将文件拖入其中并单击按钮时,文本框中的文件将移动到另一个文件夹。但是,如果我忘记将文件拖到文本框并单击按钮,程序会抛出一个参数异常,该异常不存在 sourceFileName。
private void button_Click(object sender, EventArgs e)
{
// here occurs Argument Exception Because there isn't any TextBox.Text
File.Copy(TextBox.Text, "C:/");
if (String.IsNullOrEmpty(TextBox.Text))
{
MessageBox.Show("Please drag a file to the Tex Box!");
}
}
如何捕获缺少源文件的参数异常?
在File.Copy
之前检查string.IsNullOrEmpty
,如果TextBox
为空,则从事件中return
。
private void button_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(TextBox.Text))
{
MessageBox.Show("Please drag a file to the Tex Box!");
return; // return from the event
}
File.Copy(TextBox.Text, "C:/");
}
如果您使用 string.IsNullOrWhiteSpace
也更好,因为它会检查null
、string.Empty
和空格(仅当您使用 .Net 框架 4.0 或更高版本时)
但是如果我忘记将文件拖到文本框中
然后,您需要在代码中进行一些错误检查。 如果可以在 UI 中单击按钮而不指定文件,则代码不能假定文件名将存在。 (目前确实如此。
在执行文件操作之前,请尝试检查条件:
if (!string.IsNullOrEmpty(TextBox.Text))
File.Copy(TextBox.Text, "C:/");
甚至可以更进一步来检查该值是否真的是一个有效的文件:
if (! string.IsNullOrEmpty(TextBox.Text))
if (File.Exists(TextBox.Text))
File.Copy(TextBox.Text, "C:/");
添加一些else
条件以向用户显示适当的消息。 相反,您可以在 UI 中禁用按钮,直到文本框具有值。 或者,好吧,您可以同时采用这两种方法。
(顺便说一句,TextBox
对于变量来说并不是一个特别好的名字。 这是一个实际类的名称,可能与变量本身是同一个类。 最好区分类名和变量实例名,尤其是在要对该类使用静态方法时。
将String.IsNullOrEmpty
语句移到另一个语句之前。
private void button_Click(object sender, EventArgs e)
{
if (String.IsNullOrEmpty(TextBox.Text))
MessageBox.Show("Please drag a file to the Tex Box!");
else
File.Copy(TextBox.Text, "C:/");
}
为什么要
在之后进行检查?
if (String.IsNullOrEmpty(TextBox.Text))
MessageBox.Show("Please drag a file to the Tex Box!");
else
File.Copy(TextBox.Text, "C:/");
您只想在操作有效时执行该操作。 真的,您可能需要尝试/捕获整个事情,因为可能会发生多个错误
我倾向于使用 File.Exists 来查看文件是否事先存在我喜欢在特殊情况下使用例外,但这是个人偏好
if (File.Exists(TextBox.Text.Trim()))
{
File.Copy(TextBox.Text, "C:/");
}
else
{
MessageBox.Show("Please drag a file to the Tex Box!");
return;
}