-1

Below this code is my Add button on my windows form. When i tried to click it without adding any image & without path also, error occur that i mentioned below these code. I want to fix this exception, even if the user doesn't add image or file path it doesn't get exception. I know its been asked many times but their exception in their code is different so i'm a bit confused there. Thank you

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);

        }
    }

// This is where System Argument Exception occur

        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);
  • 5
    You seem to have answered your own question. *"without adding any image & without path"* - Yes, that's exactly what the error is telling you. *"of course i will validate it as empty field"* - Yes, that's what you would need to do. So what exactly is the problem? Have you tried adding any code to check if the value is empty before trying to use the value? What didn't work? – David Aug 27 '18 at 09:40
  • @David I tried actually sir, string.IsNullOrEmpty(txt_path.Text) it doesn't work –  Aug 27 '18 at 09:47
  • 1
    Where did you try this? Because that's exactly how anybody here would validate the value, and it would work just fine if used correctly. So *what did you try* and *how did it fail*? – David Aug 27 '18 at 09:49
  • @David You can see it to my code sir. I tried to validate my textboxes and one of those is my filepath it validates all my textboxes in there expect for the textbox of file path. how did it fail ? nothing happen and it occur the exception. –  Aug 27 '18 at 09:53
  • @FeridSejdović Can you elaborate more it sir ? Thank you so much –  Aug 27 '18 at 10:01
  • Either your file is open somewhere and something holds it or the path does not exist. There is no third option. @Diether – Ferid Š. Sejdović Aug 27 '18 at 10:09
  • 1
    @Diether: *"You can see it to my code sir."* - Where in your code do you do this? The error happens on the *second line* of your method. You're certainly not doing this on the *first line*. So where *are* you doing this? It seems like the reason it fails is because you're trying to prevent the error *after* it happens. Instead, try preventing the error *before* it happens. First validate the input, *then* use the input. Instead of trying to use the input and then later validating it. – David Aug 27 '18 at 10:16
  • @FeridSejdović edited my code sir please see it –  Aug 27 '18 at 10:28
  • @David i added all my winform code there. the latest one is the event of openfiledialog where i can select the image –  Aug 27 '18 at 10:29
  • @Diether See the answer below for FileExist validation. And for example this: https://stackoverflow.com/questions/876473/is-there-a-way-to-check-if-a-file-is-in-use for the second validation. Regards. – Ferid Š. Sejdović Aug 27 '18 at 10:35

1 Answers1

1

You can either pre-check the file exists:

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
}

or catch the error when it occurs:

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.
}

As you asked about wrapping the FileStream in a using statement:

When you open a FileStream you need to explicitly close it and make sure you've disposed of it to remove the open file handle - so that other applications can access the file. You can either do this by calling Close and Dispose or you can just wrap the object in a using statement that will automatically call close and dispose for you.

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

The FileStream and BinaryReader objects (stream and read) only exist up to the point where the using statements closing brace } is.

Handbag Crab
  • 1,488
  • 2
  • 8
  • 12
  • I would add a check if file is open. – Ferid Š. Sejdović Aug 27 '18 at 10:33
  • 3
    Maybe but the question is regarding why it fails when the path is empty so rather than confuse by adding extraneous code I've kept it to the minimum to answer the question. I could have also included suggestions to wrap the FileStream and BinaryReader in using statements to ensure they're properly disposed but that's getting further away from answering the question at hand. Using the try...catch way will handle the issue of the file already being open. – Handbag Crab Aug 27 '18 at 10:37
  • This is the answer what i've been looking for. Thank you so much sir. –  Aug 27 '18 at 10:41
  • About you mention here sir " I could have also included suggestions to wrap the FileStream and BinaryReader in using statements to ensure they're properly disposed" I would love to hear that suggestion of yours i know it's out of my question already but it will help me as a developer to know that things –  Aug 27 '18 at 10:46
  • I've updated my answer to include a bit about `using` statements. – Handbag Crab Aug 27 '18 at 11:06