0

We are storing file(s) in the database using byte[] in SQL. I am trying to do a simple check to find out if the file exists before proceeding with my method.

My problem is that even attempting to check the files existence results in an exceception.

Here are the 2 attempts ive tried:

            var file = db.Attachments.Where(x => x.ResultsID == testResult).FirstOrDefault();

            if(file.Data.Length == 0)
            {
                //do stuff
            }

And this

            var file = db.Attachments.Where(x => x.ResultsID == testResult).FirstOrDefault();

            if(file.Data == null)
            {
                //do stuff
            }

Both result in null reference exceptions due to Data, a byte[] being null, not empty, due to there being no file there.

How can I check whether a db file of type byte[] exists?

Eli
  • 533
  • 1
  • 5
  • 24
  • file itself can be null, and in your cases thats what happening. Use if(file?.Data == null) – N Subedi Jun 08 '23 at 18:32
  • 1
    *"Both result in null reference exceptions due to Data, a byte[] being null"* - If the `Data` property is `null` on a non-`null` `file` object then `if(file.Data == null)` would work as expected. I suspect you've made a false assumption in your debugging. – David Jun 08 '23 at 18:33

0 Answers0