Evan Mulawski

Is it possible to compare a file's signature to a string Thank you.

Evan Mulawski




Re: Visual C# General Check file signature?

Peter Ritchie

A file's "signature" What signature are you talking about




Re: Visual C# General Check file signature?

Evan Mulawski

Like the certain signing of, say spyware (No, I'm not building spyware ), like how anti-spyware programs compare a file's signature to a definitions file.




Re: Visual C# General Check file signature?

Fernando Nicolet

Hi Evan.

I'm answering to your post asuming a couple of this... since I'm still not sure of what you want.

Most files start with a header. For example, a bmp starts with the BITMAPFILEHEADER.
Within this header usually, the first bites are a signature. For example, the BITMAPFILEHEADER start with BM.

Anyhow, I assume you will not know what your file contains... so you can't assume that it starts with text. Therefor the answer to your question is "no". What you can do is convert the string to binary and compare it with the file's first bytes.

This is:



public bool FileStartsWith (string signature, string filePath)
{
byte[] buffer = new byte[signature.Length];
FileStream fs = new FileStream(filePath,
FileMode.Open,
FileAccess.Read);
bool result = true;
if (fs.Length >= signature.Length)
{
fs.Read (buffer, 0, buffer.Length);
byte[] binaryText = System.Text.Encoding.Default.GetBytes(signature);
for (int i = 0; i < buffer.Length; i++)
{
if (binaryText[ i ] != buffer[ i ])
{
result = false;
break;
}
}
}
else
{
result = false;
}
fs.Close();
return result;
}

Of course, you should handle exceptions and such.

I hope this is what you were looking for.

Regards,
Fernando.