我正在用SQLite制作一个Winform应用程序。我正在使用将图像加载到我的C#winform应用程序中。有时用户需要添加图像,有时用户不需要添加图像。当图像加载的表单为空时,在保存表单之前,它显示异常"空路径名称不合法"。以下代码出现异常
byte[] imageBt = null;
FileStream fstream = new FileStream(this.cnicloc_txt.Text, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
我的加载图像代码如下
private void loadImage_btn_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
dlg.Filter = "JPG Files(*.jpg)|*.jpg|PNG Files(*.png)|*.png|All Files(*.*)|*.*";
dlg.Title = "Select CNIC of Owner...";
if(dlg.ShowDialog()==DialogResult.OK)
{
string picPath = dlg.FileName.ToString();
cnicloc_txt.Text = picPath;
}}
我是新来的,如果我犯了任何错误,请原谅我。
在将值传递给构造函数之前测试这些值是个好主意。测试this.cnicloc_txt.Text的值,如果为null,则中止操作。这样做:
string file = this.cnicloc_txt.Text;
if (!string.IsNullOrWhiteSpace(file))
{
byte[] imageBt = null;
FileStream fstream = new FileStream(file, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
}
快乐编码:)
if (!string.IsNullOrWhiteSpace(cnicloc_txt.Text))
{
if (!File.Exists(cnicloc_txt.Text))
{
MessageBox.Show("The file you entered does not exist.");
return;
}
// load the image....
}
对我来说,最好这样写。。
string file = this.cnicloc_txt.Text.Trim();
if (!string.IsNullOrEmpty(file))
{
byte[] imageBt = null;
FileStream fstream = new FileStream(file, FileMode.Open,
FileAccess.Read);
BinaryReader br = new BinaryReader(fstream);
imageBt = br.ReadBytes((int)fstream.Length);
}