用C#實現Java 7新方法probeContentType

來源:互聯網
上載者:User

在Java 7中增加了新的一個方法——probeContentType,其主要作用是可以判斷檔案的content type。相應代碼如下所示:

import java.io.IOException;  import java.nio.file.Files;  import java.nio.file.Path;  import java.nio.file.Paths;  public class FileContentType {      public static void main(String[] args) {                         printContentType("D:/Downloads/java.txt");          printContentType("D:/Downloads/java.ppt");          printContentType("D:/Downloads/java.doc");          printContentType("D:/Downloads/java.avi");      }      private static void printContentType(String pathToFile) {                         Path path = Paths.get(pathToFile);          String contentType = null;          try {              contentType = Files.probeContentType(path);          } catch (IOException e) {                           e.printStackTrace();          }          System.out.println("File content type is : " + contentType);      }  }

查看本欄目更多精彩內容:http://www.bianceng.cnhttp://www.bianceng.cn/Programming/csharp/

在C#中沒有對應的方法,不過要實現同樣的功能並不困難。

using System;  using System.IO;  using Microsoft.Win32;          namespace Demo  {      class Program      {          static void Main(string[] args)          {              PrintContentType("D:/Downloads/java.txt");              PrintContentType("D:/Downloads/java.ppt");              PrintContentType("D:/Downloads/java.doc");              PrintContentType("D:/Downloads/java.jar");                      Console.ReadKey();          }                  private static void PrintContentType(string pathToFile)          {              string result = string.Empty;              string ext = Path.GetExtension(pathToFile);              using (RegistryKey registryKey = Registry.ClassesRoot.OpenSubKey(ext))              {                  if (registryKey != null)                  {                      var value = registryKey.GetValue("Content Type");                      result = value == null ? "null" : value.ToString();                  }              }              Console.WriteLine(result);          }      }  }

因為相關的content type資訊其實都可以從註冊表中取得,故而只需要對註冊表做一點操作,即可以達到同樣的功能。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.