Saturday, 14 March 2015

Getting and Setting File Tag Meta Information in C# and ASP.NET - With TagLib and DsoFile Examples

The Problem
I recently developed a video content management system, and rather than store hidden files to track versioning and movement of physical files, I wanted to modify the internal file meta information of the videos themselves. I planned to stuff a database ID into the comment tag within each video file, but this proved to be very challenging given the very disoraganised way in which various operating system handled different file types.

Possible Solutions
MediaInfo - Cool API, updated a lot, but there is no support for setting file meta information. The entire API is READ ONLY!

TagLib - Again, good API with scope to set file tag meta information. So I decided to try this API out and see how far I could get with it. I started hitting it's limits when I couldn't set file meta information for a LOT of video file types: MKV, MOV, 3GP, ASF and more.

DsoFile - Microsoft's answer to tagging Microsoft Office file tag information. It's able to set Office file tags but also totally new custom properties within each file. You cannot see these values in Windows Explorer without a handy Powershell script plugin, but it works for ALL file types, not just office documents. It's written in C++ and includes the source code also. The downside is that it's a COM component, 32bit and no longer supported. However, somebody compiled a 64bit version here

The Ideal Solution
DsoFile seems like a great solution to the problem. TagLib works hard to achieve an ideal solution, but there are too many file types out there ever changing and the library finds it hard to keep up. I decided to use DsoFile for my project for the time being. I have provided some sample code below so you can see how TagLib and DsoFile libraries modify file meta tag information.

TagLib Sample Code - How to Get and Set the Comment File Meta Tag Field
Code Snippet
  1. using System;
  2. using TagLib;
  4. /// <summary>
  5. /// (c)
  6. /// This sample class enables you to set meta file information within physical files.
  7. /// This is similar to EXIF information for picture files.
  8. /// TagLib doesn't seem to work for a lot of file types: MKV, MOV etc
  9. /// It seems to work ok for MP4 files though.
  10. /// </summary>
  11. public static class TagLibExample
  12. {
  13.     /// <summary>
  14.     /// Gets the comment tag from a files meta information
  15.     /// </summary>
  16.     /// <param name="filename">Path to the file</param>
  17.     /// <returns>Our custom value stored in the files comment tag</returns>
  18.     public static string GetCommentField(string filename)
  19.     {
  20.         string comment = string.Empty;
  21.         TagLib.File file = null;
  23.         try
  24.         {
  25.             file = TagLib.File.Create(filename);
  26.             comment = file.Tag.Comment;
  27.         }
  28.         catch (Exception ex)
  29.         {
  30.             // This library works with limited file types, so unsupported file types are
  31.             // thrown here when trying to use "TagLib.File.Create()"
  32.         }
  33.         finally
  34.         {
  35.             if (file != null) file.Dispose(); // Clean up
  36.         }
  38.         return comment;
  39.     }
  41.     /// <summary>
  42.     /// Sets the comment tag within a files meta information
  43.     /// </summary>
  44.     /// <param name="filename">Path to the file</param>
  45.     /// <param name="value">Value to store in the comment tag</param>
  46.     public static void SetCommentField(string filename, string value)
  47.     {
  48.         TagLib.File file = null;
  50.         try
  51.         {
  52.             file = TagLib.File.Create(filename);
  54.             // Set comment tag
  55.             // NOTE: file.Tag.Comment cannot be an empty string, it defaults to null if empty
  56.             file.Tag.Comment = GetCommentField;
  57.             file.Save();
  59.             // Check comment was added successfully.
  60.             // For some reason, TagLib won't throw an error if the property doesnt save
  61.             // for certain file types, yet they appear to be supported.
  62.             // So we have to check it actually worked...
  63.             file = TagLib.File.Create(filename);
  65.             if (file.Tag.Comment != value)
  66.                 throw new Exception("Could not set comment tag. This file format is not supported.");
  67.         }
  68.         catch (Exception ex)
  69.         {
  70.             // Handle errors here
  71.         }
  72.         finally // Always called, even when throwing in Exception block
  73.         {
  74.             if (file != null) file.Dispose(); // Clean up
  75.         }
  76.     }
  77. }
End of Code Snippet

DsoFile Sample Code - How to Store a Value into a Custom Property and Get it back!
Code Snippet
  1. using System;
  2. using DSOFile;
  4. /// <summary>
  5. /// (c)
  6. /// This sample class enables you to set meta file information within physical files.
  7. /// This is similar to EXIF information for picture files.
  8. /// DSOFile works for every file type, not just office files.
  9. ///
  10. /// NOTE
  11. /// DsoFile is an unmnaged 32bit dll. We need to compile in x86 mode or we get 'class not registered exception'
  12. /// There is a third party 64bit version available online, or recompile the C++ source manually.
  13. /// </summary>
  14. public static class DSOFileExample
  15. {
  16.     /// <summary>
  17.     /// A property name that this sample code uses to store tag information.
  18.     /// </summary>
  19.     private static string FILE_PROPERTY = "CustomFileTag";
  21.     /// <summary>
  22.     /// Gets value stored in a custom tag
  23.     /// </summary>
  24.     /// <param name="filename">Path to the file</param>
  25.     /// <returns>Our custom value stored in the custom file tag</returns>
  26.     public static string GetCustomPropertyValue(string filename)
  27.     {
  28.         string comment = string.Empty;
  29.         OleDocumentProperties file = new DSOFile.OleDocumentProperties();
  31.         try
  32.         {
  33.             // Open file
  34.             file.Open(filename, false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
  35.             comment = GetTagField(file);
  36.         }
  37.         catch (Exception ex)
  38.         {
  39.             // Handle errors here
  40.         }
  41.         finally
  42.         {
  43.             if (file != null) file.Close(); // Clean up
  44.         }
  46.         return comment;
  47.     }
  49.     /// <summary>
  50.     /// Sets value stored in a files custom tag
  51.     /// </summary>
  52.     /// <param name="filename">Path to the file</param>
  53.     /// <param name="value">Value to store in the custom file tag</param>
  54.     public static void SetCustomPropertyValue(string filename, string value)
  55.     {
  56.         OleDocumentProperties file = new DSOFile.OleDocumentProperties();
  58.         try
  59.         {
  60.             file.Open(filename, false, DSOFile.dsoFileOpenOptions.dsoOptionDefault);
  61.             SetTagField(file, value);
  62.         }
  63.         catch (Exception ex)
  64.         {
  65.             // Handle errors here
  66.         }
  67.         finally // Always called, even when throwing in Exception block
  68.         {
  69.             if (file != null) file.Close(); // Clean up
  70.         }
  71.     }
  73.     /// <summary>
  74.     /// Gets the value of the file tag property
  75.     /// </summary>
  76.     /// <param name="file">Ole Document File</param>
  77.     /// <returns>Contents of the file tag property. Can be null or empty.</returns>
  78.     private static string GetTagField(DSOFile.OleDocumentProperties file)
  79.     {
  80.         string result = string.Empty;
  81.         foreach (DSOFile.CustomProperty property in file.CustomProperties)
  82.         {
  83.             if (property.Name == FILE_PROPERTY) // Check property exists
  84.             {
  85.                 result = property.get_Value();
  86.                 break;
  87.             }
  88.         }
  89.         return result;
  90.     }
  92.     /// <summary>
  93.     /// Sets the value of the file tag property
  94.     /// </summary>
  95.     /// <param name="file">Ole Document File</param>
  96.     /// <param name="value">Value to set as the property value</param>
  97.     /// <param name="saveDocument">Saves document if set to true</param>
  98.     /// <param name="closeDocument">Closes the document if set to true</param>
  99.     private static void SetTagField(DSOFile.OleDocumentProperties file, string value, bool saveDocument = true, bool closeDocument = true)
  100.     {
  101.         bool found = false;
  102.         foreach (DSOFile.CustomProperty property in file.CustomProperties)
  103.         {
  104.             if (property.Name == FILE_PROPERTY) // Check property exists
  105.             {
  106.                 property.set_Value(value);
  107.                 found = true;
  108.                 break;
  109.             }
  110.         }
  112.         if (!found)
  113.             file.CustomProperties.Add(FILE_PROPERTY, value);
  115.         if (saveDocument)
  116.             file.Save();
  118.         if (closeDocument)
  119.             file.Close();
  120.     }
  121. }
End of Code Snippet


Unknown said...

Congratulations! Extremely useful... I'll try to do that in my project too... Do you no if its possible to add a read only tag... Avoiding future modifications on tags?

Manoj Kumar M said...

Nice information. Is it or windows filesystem, I mean, if we set a metadata of a video file in windows and copy it to Linux, does the metadata show up there too?.

Mumbai Escorts said...

Mumbai Escorts, VIP escorts in Mumbai
Celebrity Escorts Mumbai
Mumbai escorts, Escorts in Mumbai
Escorts service in Mumbai
Delhi Escorts, Escorts services in Delhi
Escort girls in Mumbai, Escorts in Mumbai
mumbai escorts, VIP escorts in mumbai
Escorts Mumbai

Anonymous said...

Delhi Escorts, VIP escorts Delhi
Escorts in Delhi, Delhi Escorts
High profile Escorts in Delhi
Escorts Service in Delhi
Escorts Service in Delhi
Dwarka Escorts, Escorts in Dwarka
Escorts Service in Delhi

Delhi Escorts said...

Escorts Girls in Gurgaon
Independent Escort in Delhi, delhi escorts
Gurgaon Escorts, Escorts Service in Gurgaon
Escorts Service in Delhi
Escort Service in Delhi, Top Class Girl
Deshi Escorts: Escorts Service in Gurugram
Escorts Girls in Mumbai, Mumbai Escorts

rmouniak said...

It'sVery informative blog and useful article thank you for sharing with us , keep posting learn more
.NET Online Course Hyderabad

michaelwaung said...

Thanks for sharing this informative blog. Such a useful Blog. I hope to keep sharing this type of blog.

Website Meta Tag Extractor

teo said...

Thanks for this!
any sample of the "handy Powershell script plugin" to see these values in Windows Explorer?

escort datting said...

We can contact you at our WhatsApp number to join Kotputli Escorts Independent Celebrity Call Girls Service in Katputli, in Kotputli, meeting with our high class Affair Rate Model VIP Women Premium Call Girls Agency.Katputali Escort

Call Girls In Gurgaon With Whatsapp Number said...

Welcome to Gurgaon Escorts Agency, we give you complete discount of receiving Russian and erotic call girls in Gurgaon, you can contact us on our website to get them. Call Girls In Gurgaon With Whatsapp Number

gurgaon escort said...

When it comes to dating professional Call Girls In Delhi With Photo and Mobile Number, there are many aspects which you should consider as escort dating is not as simple as it seems. Needless to mention, it is more about having erotic fun with the Cheap Girls.Female Escort in Delhi With Photo

mumbaigirls said...

Want to experiment pleasure and excitement in life? We have the perfect answer to your imagination! Enjoy the warm company of Call Girls in Delhi With Photo and take your senses to a new level of pleasure. When it comes to providing best Delhi girls, Mobile no one does it better than us. Delhi Escorts With Photos

Andheri Escorts Love said...

Escorts Goa
Escorts Panaji

Escorts Bangalore
Escorts In Bangalore
Escorts Services Bangalore
MG Road Escorts
Jayanagar Escorts
JP Nagar Escorts
Koramangala Escorts
Whitefield Escorts

Chandigarh Escorts said...

Visit here___

Chandigarh Escorts--->>

Chandigarh Escort--->>

Chandigarh Independent Escorts--->>

Chandigarh Call Girls--->>

Chandigarh Escort Service--->>

Escort In Chandigarh--->>

Escorts In Chandigarh--->>

Chandigarh Escorts Services--->>

Chandigarh Call Girl--->>

Chandigarh Escorts said...

Visit here___

Independent escort in Chandigarh--->>

Independent Escorts In Chandigarh--->>

Chandigarh Independent Escorts--->>

Chandigarh Independent Escort--->>

Chandigarh call girls center--->>

Chandigarh call girls--->>

Chandigarh call girl--->>

call girls in Chandigarh--->>

call girl in Chandigarh--->>

Chandigarh Escorts said...

Visit here___

independent call girls in Chandigarh--->>

independent call girl in Chandigarh--->>

Chandigarh call girls number--->>

Chandigarh call girl number--->>

Escort Service In Chandigarh--->>

Escorts Services In Chandigarh--->>

Call Girls--->>

Call Girl--->>

Simran said...

………… /´¯/) click for supper hot sexy escort Service girls
……….,/¯../ /
………/…./ /
(‘(…´…´…. ¯_/’…’/
..\’…\………. _.•´
Visit here___

Chandigarh Call Girl | Chandigarh Call Girls

Chandigarh Escort | Chandigarh Escorts

Chandigarh Escort Service | Chandigarh Escorts Services

Escort In Chandigarh | Escorts In Chandigarh

Call Girl In Chandigarh | Call Girls In Chandigarh

Escort Service In Chandigarh | Escorts Services In Chandigarh

Chandigarh Independent Escort | Chandigarh Independent Escorts

Janu said...

Good job in presenting the correct content with the clear explanation. The content looks real with valid information.

Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery

Elite Escorts Agency Delhi 9818-254757 said...

In these companies most attractive and elegant girls are working and when you will come across these ladies you will always feel horny. The people who want to spend time with sexy and elegant ladies can now hire our Delhi escorts. Our escorts are the best for men who are feeling lonely and sexually frustrated. We are offering our best escorts in this location of Delhi so that we can meet the choice of elite class men of the society. Thus, when you will be hiring our escort services you will always feel delighted.

Escorts Service In Delhi

Aerocity Escorts

Mahipalpur Escorts

Connaught Place Escorts

Karol Bbagh Escorts

Paharganj Escorts

Elite Escorts Agency Delhi 9818-254757 said...

We can assure that we have different range of service ingredients stocked where you will find elite escort services, medium range and cheap ones too. We keep these type of ranges in order to be able to cater all kinds of clients. Some clients want to have the luxurious services including of all kinds of facilities and some simply want to medium range services such as housewife, home-makers, college going girls etc. But there are many who want to have nightstand with beautiful air-hostesses etc. and no matter what type of escort our clients want, we accordingly present them all those kinds to cater and satisfy their needs.

Call Girls In Delhi

Rohini Escorts

Laxmi Nagar Escorts

Paschim Vihar escorts

Shahdara Escorts

Delhi Escorts said...

For information about call girls in Connaught Place, you can get information by reading our blog, you can get call girls service in Connaught Place anytime. Escort service in connaught place

Andheri Escorts Love said...

Bangalore Escorts
Bangalore Escorts
Bangalore Escorts
Escorts Kolkata
Escorts Dumdum
Escorts Park Street
Escorts Salt Lake
Escorts Howrah
Escorts Maheshtala

Andheri Escorts Love said...

Escorts Tajpur
Ashok Nagar Escorts
Alipore Escorts
Bhatpara Escorts
Behala Escorts
Belgachia Escorts
Bara Bazar Escorts
Ballygunge Escorts
Dharmatala Escorts

Andheri Escorts Love said...

Hyderabad Escorts
Jubilee Hills Escorts
Banjara Hills Escorts
Visakhapatnam Escorts
Secunderabad Escorts
Hitech City Escorts
Secunderabad Escorts
Somajiguda Escorts
Begumpet Escorts

Andheri Escorts Love said...

Manikonda Escorts
Uppal Escorts
Kukatpally Escorts
Miyapur Escorts
Market Street Escorts
Somajiguda Escorts
Doodh Bowli Escorts
Hill Fort Escorts said...

Thanks for sharing .You have done a fantastic work on this short article.
Delhi Escorts
Delhi Escorts Service
Geeta AggerwalEscort Service In Delhi
Anika Chaudhary Delhi Escort
Priya Roy Delhi Escort Service