标签归档:MIME

IIS MIME类型显示与设置编程实现

用 System.DirectoryServices为IIS设置MIME类型
设置IIS MIME类型

using System;
using System.IO;
using System.DirectoryServices;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Collections;

namespace System_DirectoryServices_DirectoryEntry_ConfigIIS
{
  class Program
  {
    static void Main(string[] args)
    {
        SetMimeTypeProperty("IIS://localhost/W3SVC/1/Root", ".hlp", "application/winhlp");
    }

    static void SetMimeTypeProperty(string metabasePath, string newExtension, string newMimeType)
    {
      //  metabasePath is of the form "IIS://<servername>/<path>"
      //    for example "IIS://localhost/W3SVC/1/Root" 
      //  newExtension is of the form ".<extension>", for example, ".hlp"
      //  newMimeType is of the form "<application>", for example, "application/winhlp"
      Console.WriteLine("\nAdding {1}->{2} to the MimeMap property at {0}:", metabasePath, newExtension, newMimeType);

      try
      {
          DirectoryEntry path = new DirectoryEntry(metabasePath);
          PropertyValueCollection propValues = path.Properties["MimeMap"];
          Console.WriteLine(" Old value of MimeMap has {0} elements", propValues.Count);

          object exists = null;
          foreach (object value in propValues)
          {
              // IISOle requires a reference to the Active DS IIS Namespace Provider in Visual Studio .NET
              IISOle.IISMimeType mimetypeObj = (IISOle.IISMimeType)value;
              Console.WriteLine("  {0}->{1}", mimetypeObj.Extension, mimetypeObj.MimeType);
              if (newExtension == mimetypeObj.Extension)
                  exists = value;
          }

          if (null != exists)
          {
              propValues.Remove(exists);
              Console.WriteLine(" Found an entry for {0}; removing it before adding the new one.", newExtension);
          }

          IISOle.MimeMapClass newObj = new IISOle.MimeMapClass();
          newObj.Extension = newExtension;
          newObj.MimeType = newMimeType;
          propValues.Add(newObj);
          path.CommitChanges();
          Console.WriteLine(" Done.");

      }
      catch (Exception ex)
      {
          if ("HRESULT 0x80005006" == ex.Message)
              Console.WriteLine(" Property MimeMap does not exist at {0}", metabasePath);
          else
              Console.WriteLine("Failed in SetMimeTypeProperty with the following exception: \n{0}", ex.Message);
      }    
    }
  }
}

继续阅读