|
1 | | -# File type interrogator |
| 1 | +# FileTypeInterrogator |
2 | 2 |
|
3 | | -Determine file type by 'Magic Numbers' for most common file types instead of trusting file extensions |
| 3 | +netstandard library for detecting file types by 'magic numbers', similar to the `file` command in Linux/Unix. Useful for validating file uploads instead of trusting file extensions. |
4 | 4 |
|
5 | | -# License |
| 5 | +# Usage |
6 | 6 |
|
7 | | - Copyright 2018 Daniel Destouche |
| 7 | +``` |
| 8 | +IFileTypeInterrogator interrogator = new FileTypeInterrogator(); |
8 | 9 |
|
9 | | - Licensed under the Apache License, Version 2.0 (the "License"); |
10 | | - you may not use this file except in compliance with the License. |
11 | | - You may obtain a copy of the License at |
| 10 | +byte[] fileBytes = File.ReadAllBytes("pdfFile.pdf"); |
12 | 11 |
|
13 | | - http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +FileTypeInfo fileTypeInfo = interrogator.DetectType(fileBytes); |
14 | 13 |
|
15 | | - Unless required by applicable law or agreed to in writing, software |
16 | | - distributed under the License is distributed on an "AS IS" BASIS, |
17 | | - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
18 | | - See the License for the specific language governing permissions and |
19 | | - limitations under the License. |
| 14 | +Console.WriteLine("Name = " + fileTypeInfo.Name); |
| 15 | +Console.WriteLine("Extension = " + fileTypeInfo.FileType); |
| 16 | +Console.WriteLine("Mime Type = " + fileTypeInfo.MimeType); |
| 17 | +
|
| 18 | +// The following output would be displayed: |
| 19 | +// Name = Portable Document Format File |
| 20 | +// Extension = pdf |
| 21 | +// Mime Type = application/pdf |
| 22 | +``` |
| 23 | + |
| 24 | +Notice that `IFileTypeInterrogator` was assigned, meaning custom implementations are welcomed. File definitions are provided in the source and will be regularly updated, feel free to submit an issue or pull request to add other signatures. To quickly provide support for a new signature, create an instance of `CustomFileTypeInterrogator`: |
| 25 | + |
| 26 | +``` |
| 27 | +IFileTypeInterrogator interrogator = new CustomFileTypeInterrogator("path_to_custom_definitions_file", Encoding.UTF8); |
| 28 | +
|
| 29 | +FileTypeInfo fileTypeInfo = interrogator.DetectType(...); |
| 30 | +``` |
| 31 | + |
| 32 | +It is best to create a single instance and manage it's lifetime through an IOC/DI Container. |
0 commit comments