4 // Copyright (C) 2006 Debajyoti Bera
8 // Permission is hereby granted, free of charge, to any person obtaining a
9 // copy of this software and associated documentation files (the "Software"),
10 // to deal in the Software without restriction, including without limitation
11 // the rights to use, copy, modify, merge, publish, distribute, sublicense,
12 // and/or sell copies of the Software, and to permit persons to whom the
13 // Software is furnished to do so, subject to the following conditions:
15 // The above copyright notice and this permission notice shall be included in
16 // all copies or substantial portions of the Software.
18 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
23 // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
24 // DEALINGS IN THE SOFTWARE.
30 using System
.Runtime
.InteropServices
;
33 namespace Beagle
.Util
{
34 public class XdgMime
{
36 [DllImport ("libbeagleglue")]
37 static extern IntPtr
xdg_mime_get_mime_type_for_file (string file_path
, IntPtr optional_stat_info
);
39 public static string GetMimeType (string file_path
)
41 string mime_type
= Marshal
.PtrToStringAnsi (xdg_mime_get_mime_type_for_file (file_path
, (IntPtr
) null));
43 if (mime_type
!= "application/octet-stream")
46 // xdgmime recognizes most files without extensions as
47 // application/octet-stream. Check the first 256 bytes
48 // to see if it's really plain text.
49 if (ValidateUTF8 (file_path
))
55 private static UTF8Encoding validating_encoding
= new UTF8Encoding (true, true);
57 private static bool ValidateUTF8 (string file_path
)
62 fs
= new FileStream (file_path
, FileMode
.Open
, FileAccess
.Read
, FileShare
.Read
);
63 } catch (IOException
) {
67 byte[] byte_buf
= new byte [256];
68 char[] char_buf
= new char [256];
70 int buf_length
= fs
.Read (byte_buf
, 0, 256);
75 return false; // Don't treat empty files as text/plain
77 Decoder d
= validating_encoding
.GetDecoder ();
80 d
.GetChars (byte_buf
, 0, buf_length
, char_buf
, 0);
82 // FIXME: UTF8 allows control characters in a file.
83 // Should we allow control characters in a text file?
84 } catch (ArgumentException ex
) {