ShiningLea
ShiningLea

Reputation: 162

How to check if a file's content is filled with white spaces/nulls/0s?

So currently I'm coding a file scanner with signature checking. But I have a problem, there are files that are detected by infected by the program but they are protected operating system files. So I took a look at the two files' contents, and they were the same.

In Sublime Text, they were filled with zeros, like a binary file but only with zeros.

In Notepad++, they were filled with NULs.

And in classic Notepad, I just saw white spaces.

So I've tried multiple solutions, the first was to check if the file was null or filled with white spaces with the following code :

if (string.IsNullOrWhiteSpace(File.ReadAllText(TextBox1.Text)))
                    MessageBox.Show("yes");

Assuming TextBox1.Text is the file path. Sadly, that code didn't work. So I've tried but with IsNullOrEmpty :

if (string.IsNullOrEmpty(File.ReadAllText(TextBox1.Text)))
                    MessageBox.Show("yes");

But still the same result. Finally, since the files' content were technically null, I've decided to check if they were null with the following code :

if (File.ReadAllText(TextBox1.Text) == null)
                    MessageBox.Show("yes");

But that also didn't work.

Is there a solution to this problem or do I have to skip protected operating system files?

Upvotes: 0

Views: 946

Answers (1)

Caius Jard
Caius Jard

Reputation: 74605

I'm not sure you'll get a good result with using strings, you should read bytes instead:

byte[] ba = File.ReadAllBytes(...);

if(ba.All(b => b == 0))
  //file is all zero filled

Beware naively reading all bytes from a file into memory; plenty of files on the users drive may exceed the maximum size a .net object may be (or easily exceed the memory installer in the machine). Consider reading them gradually with a stream instead; the logic for a binary file could be to read it until you hit a non zero byte. If you reach the end o the file without finding one, it was all zero

you didn't say what else you're doing with your files so it's hard to advise

Upvotes: 2

Related Questions