Is it possible to compare a file's signature to a string Thank you.
Evan Mulawski
Visual C# General
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.