C # Пустое имя пути недопустимо - Winform - PullRequest
0 голосов
/ 27 августа 2018

Ниже этого кода находится моя кнопка Добавить в моей форме окна. Когда я пытался щелкнуть по нему без добавления какого-либо изображения и без пути, также произошла ошибка, о которой я упоминал под этим кодом. Я хочу исправить это исключение, даже если пользователь не добавляет изображение или путь к файлу, он не получает исключение. Я знаю, что об этом спрашивали много раз, но их исключения в коде отличаются, поэтому я немного запутался. Спасибо

private void btn_add_Click(object sender, EventArgs e)
    {
        byte[] image = null;
        var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
        var read = new BinaryReader(stream);
        image = read.ReadBytes((int)stream.Length);


        using (var con = SQLConnection.GetConnection())
        {


            if (string.IsNullOrEmpty(cbox_supplier.Text) || string.IsNullOrEmpty(txt_code.Text) || string.IsNullOrEmpty(txt_item.Text) || string.IsNullOrEmpty(txt_quantity.Text) || string.IsNullOrEmpty(txt_cost.Text) || string.IsNullOrEmpty(txt_path.Text))
            {
                MetroMessageBox.Show(this, "Please input the Required Fields", "System Message:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
            else
            {

                var selectCommand = new SqlCommand("Insert into employee_product (Image, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (@Image, @Supplier, @Codeitem, @Itemdescription, @Date, @Quantity, @Unitcost)",con);
                selectCommand.Parameters.AddWithValue("@Image", image);
                selectCommand.Parameters.AddWithValue("@Supplier", cbox_supplier.Text);
                selectCommand.Parameters.AddWithValue("@Codeitem", txt_code.Text.Trim());
                selectCommand.Parameters.AddWithValue("@Itemdescription", txt_item.Text.Trim());
                selectCommand.Parameters.AddWithValue("@Date", txt_date.Text.Trim());
                selectCommand.Parameters.AddWithValue("@Quantity", txt_quantity.Text.Trim());
                selectCommand.Parameters.AddWithValue("@Unitcost", txt_cost.Text.Trim());
                selectCommand.ExecuteNonQuery();
                MessageBox.Show("Added successfully", "SIMS", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
                txt_path.Clear();
                pictureBox1.Image = null;
                txt_code.Clear();
                txt_item.Clear();
                txt_quantity.Clear();
                txt_cost.Clear();
                _view.AddingProduct();

            }

        }
    }
   private void btn_upload_Click(object sender, EventArgs e)
    {
        OpenFileDialog opnfd = new OpenFileDialog();
        opnfd.Filter = "Image Files (*.jpg;*.jpeg;.*.gif;*.png;)|*.jpg;*.jpeg;.*.png;*.gif";
        opnfd.Title = "Select Item";

        if (opnfd.ShowDialog() == DialogResult.OK)
        {
            var path = opnfd.FileName.ToString();
            txt_path.Text = path;
            pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
            pictureBox1.Image = Image.FromFile(opnfd.FileName);

        }
    }

// Здесь происходит исключение системного аргумента

        byte[] image = null;
 -----> var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
        var read = new BinaryReader(stream);
        image = read.ReadBytes((int)stream.Length);

1 Ответ

0 голосов
/ 27 августа 2018

Вы можете предварительно проверить, существует ли файл:

if (File.Exists(txt_path.Text))
{
    var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
    var read = new BinaryReader(stream);
    image = read.ReadBytes((int)stream.Length);
    // The rest of your code
}

или перехватите ошибку, когда она возникнет:

try
{
    var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read);
    var read = new BinaryReader(stream);
    image = read.ReadBytes((int)stream.Length);
    // The rest of your code
}
catch
{
    // Creating filestream object failed.
}

Как вы и просили обернуть FileStream в оператор using:

Когда вы открываете FileStream, вам необходимо явно закрыть его и убедиться, что вы удалили его, чтобы удалить дескриптор открытого файла, чтобы другие приложения могли получить доступ к файлу. Вы можете сделать это, вызвав Close и Dispose, или вы можете просто обернуть объект в оператор using, который автоматически вызовет close и dispose для вас.

using (var stream = new FileStream(this.txt_path.Text, FileMode.Open, FileAccess.Read))
{
    using (var read = new BinaryReader(stream))
    {
        image = read.ReadByres((int)stream.Length);
    } // BinaryReader is Closed and Disposed here
} // FileStream is Closed and Disposed here

Объекты FileStream и BinaryReader (stream и read) существуют только до точки, в которой оператор using закрывающей скобки } равен.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...