有些时候不要;我不想添加静止显示“;空的路径名称在c#中是不合法的;

本文关键字:路径名 不合法 显示 候不 我不想 静止 添加 | 更新日期: 2023-09-27 18:21:31

我正在用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;
}}

我是新来的,如果我犯了任何错误,请原谅我。

有些时候不要;我不想添加静止显示“;空的路径名称在c#中是不合法的;

在将值传递给构造函数之前测试这些值是个好主意。测试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);
}