Click here to Skip to main content
15,887,683 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I use the code shown to try to validate my image. Unfortunately, I failed to do that and this is the first time I'm doing a validation for image. Is there anything wrong in my logic? Did I forgot something here? What's the right way in doing these. I hope someone would be able to help me thank you

System.IO.FileNotFoundException: 'Could not find file 'C:\Users\Andrea\source\repos\CapstoneSIMS\CapstoneSIMS\bin\Debug\72EF99A3668CF13820B113EB2E090C37716C9742'.' (I'M getting these error when i tried to insert image)

NOTE: I'm saving the image as image not path and also the datatype is `Varbinary(MAX)` in my database


What I have tried:

<pre lang="c#">
    public partial class ADDProduct : MetroForm
    {
        SIMSProduct _view;

        public ADDProduct(SIMSProduct _view)
        {
            InitializeComponent();
            this._view = _view;                  
        }

        DataSet ds = new DataSet();
        DataTable dt = new DataTable();
        byte[] photobyte;
        public string CalculateHash(string filename)
        {
            SHA1CryptoServiceProvider crypt = new SHA1CryptoServiceProvider();
            //MD5CryptoServiceProvider crypt = new MD5CryptoServiceProvider();
            string hash = string.Empty;
            using (FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                byte[] checksum = crypt.ComputeHash(fs);
                foreach (byte b in checksum)
                    hash += b.ToString("X2");
            }

            return (hash);
        }
    public static bool ImageExists(string filehash)
        {
            bool result = false;
            using (var connection = SQLConnection.GetConnection())
            {
                using (SqlCommand cmd = new SqlCommand("SELECT COUNT(0) FROM employee_product WHERE ImageHash = @ImageHash", connection))
                {
                    connection.Open();
                    int imagecount = (int)cmd.ExecuteScalar();
                    result = imagecount == 0;
                    connection.Close();
                }
            }

            return (result);
        }
        private void btn_add_Click(object sender, EventArgs e)
        {
            _view.ID = txt_id.Text;
            filehash = CalculateHash(@"C:\myimagefile.jpg");
            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) || pictureBox1.Image == null )
                {
                    CustomNotifcation.Show("Please input the required fields", CustomNotifcation.AlertType.warning);
                }
                else
                {          
                    ValidateCode.IsValidCode(txt_code,lbl_code,ds);
                    string filehash = CalculateHash(pictureBox1.Tag.ToString());

                    if (lbl_code.Visible == true)
                    {
                        CustomNotifcation.Show("CODE ALREADY EXIST", CustomNotifcation.AlertType.error);
                        lbl_code.Visible = false;                      
                    }
                    else if (ImageExists(pictureBox1.Tag.ToString()))
                    {
                        MessageBox.Show("image exists");
                        return;
                    }
                    else
                    {
                         using (var select = new SqlCommand("Insert into employee_product (Image, ImageHash, ID, Supplier, Codeitem, Itemdescription, Date, Quantity, Unitcost) Values (@Image, @ID, @Supplier, @Codeitem, @Itemdescription, @Date, @Quantity, @Unitcost)", con))
                            {                               
                                var ms = new MemoryStream();
                                pictureBox1.Image.Save(ms, pictureBox1.Image.RawFormat);
                                photobyte = ms.GetBuffer();
                                select.Parameters.Add("@Image", SqlDbType.VarBinary).Value = photobyte;
                                select.Parameters.Add("@ImageHash", SqlDbType.VarChar, 50);
                                select.Parameters["@ImageHash"].Value = filehash;
                                select.Parameters.Add("@Supplier", SqlDbType.VarChar).Value = cbox_supplier.Text;
                                select.Parameters.Add("@Codeitem", SqlDbType.VarChar).Value = txt_code.Text.Trim();
                                select.Parameters.Add("@Itemdescription", SqlDbType.VarChar).Value = txt_item.Text.Trim();
                                select.Parameters.Add("@Date", SqlDbType.VarChar).Value = date;
                                select.Parameters.Add("@Quantity", SqlDbType.Int).Value = txt_quantity.Text.Trim();
                                select.Parameters.Add("@Unitcost", SqlDbType.Int).Value = txt_cost.Text.Trim();
                                select.ExecuteNonQuery();
                                CustomMessage.Show("Message: Item successfully added!",CustomMessage.Messagetype.Success);
                                pictureBox1.Image = null;
                                cbox_supplier.Items.Clear();
                                txt_code.Clear();
                                txt_item.Clear();
                                txt_quantity.Clear();
                                txt_cost.Clear();
                                _view.btn_update.Enabled = false;
                                _view.AddingProduct();
                                this.Close();
                            }
                        }                
                    }                
                }
        }

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

            if (opnfd.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.SizeMode    = PictureBoxSizeMode.StretchImage;
                pictureBox1.Image       = Image.FromFile(opnfd.FileName);
                CalculateHash(opnfd.FileName);
            }
        }
    }
Posted
Updated 15-Sep-18 6:07am
v2

1 solution

This is one of the most common problems we get asked, and it's also the one we are least equipped to answer, but you are most equipped to answer yourself.

Let me just explain what the error means: You have tried to use a variable, property, or a method return value but it contains null - which means that there is no instance of a class in the variable.
It's a bit like a pocket: you have a pocket in your shirt, which you use to hold a pen. If you reach into the pocket and find there isn't a pen there, you can't sign your name on a piece of paper - and you will get very funny looks if you try! The empty pocket is giving you a null value (no pen here!) so you can't do anything that you would normally do once you retrieved your pen. Why is it empty? That's the question - it may be that you forgot to pick up your pen when you left the house this morning, or possibly you left the pen in the pocket of yesterdays shirt when you took it off last night.

We can't tell, because we weren't there, and even more importantly, we can't even see your shirt, much less what is in the pocket!

Back to computers, and you have done the same thing, somehow - and we can't see your code, much less run it and find out what contains null when it shouldn't.
But you can - and Visual Studio will help you here. Run your program in the debugger and when it fails, VS will show you the line it found the problem on. You can then start looking at the various parts of it to see what value is null and start looking back through your code to find out why. So put a breakpoint at the beginning of the method containing the error line, and run your program from the start again. This time, VS will stop before the error, and let you examine what is going on by stepping through the code looking at your values.

But we can't do that - we don't have your code, we don't know how to use it if we did have it, we don't have your data. So try it - and see how much information you can find out!
 
Share this answer
 
Comments
xdiet 15-Sep-18 12:07pm    
Already updated my question for that
OriginalGriff 15-Sep-18 12:16pm    
So your error is now "System.IO.FileNotFoundException: 'Could not find file 'C:\Users\Andrea\source\repos\CapstoneSIMS\CapstoneSIMS\bin\Debug\72EF99A3668CF13820B113EB2E090C37716C9742'.'"

Well - that's pretty obvious, isn't it? :laugh:
Three possibilities:
1) The file doesn't exist. You have checked, yes?
2) You forgot the extension when you tried to open it.
3) It's there - but on a different system, so it can't be accessed.

Again, we can't check any of that!
xdiet 15-Sep-18 20:56pm    
Well your answer doesn't answer my question, you just elaborate it
OriginalGriff 16-Sep-18 2:03am    
That's because - as I said - we can't look at your system, your data, and your code while it's running - only you can do that!
And that is exactly what is needed here: looking at the system, the data, and the code using the debugger.

Think of it like this: your car breaks down in the middle of nowhere. You can text the garage but that's all the communications you have. How can they "hear" what the engine is sounding like? See the smoke coming out the back? Check the tire pressures? Can they unbolt the air filter?

Sometimes, the only person who can solve the problem is you because only you have any access to the information.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900