2013-10-16 68 views
2

我想知道是否某個任意路徑引用了本地文件系統對象,而不是位於網絡共享位置或可移動驅動器上。有沒有辦法在.NET中做到這一點?如何檢查路徑是否指向本地文件對象?

PS。換句話說,如果我有硬盤驅動器C:和d:和驅動器E:是DVD驅動器或USB閃存驅動器,然後:

下面的路徑將是本地:

C:\Windows 
D:\My Files\File.exe 

而以下路徑將不會:

E:\File on usb stick.txt 
\\computer\file.ext 
+0

DriveInfo類將告訴您它來自驅動器號的驅動器的類型。 – PhoenixReborn

+0

這個問題似乎已經在[此線索]有了答案[1] [1]:http://stackoverflow.com/questions/2455348/check-whether-a-folder-is-a - 本地或網絡資源網 – Brennan

回答

2
using System; 
using System.IO; 

namespace random 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

      DriveInfo[] allDrives = DriveInfo.GetDrives(); 

      //TEST HERE 
      bool isFixed = allDrives.First(x=>x.Name == "D").DriveType == DriveType.Fixed 

      foreach (DriveInfo d in allDrives) 
      { 
       Console.WriteLine("Drive {0}", d.Name); 
       Console.WriteLine(" File type: {0}", d.DriveType); 
       if (d.IsReady == true) 
       { 
        Console.WriteLine(" Volume label: {0}", d.VolumeLabel); 
        Console.WriteLine(" File system: {0}", d.DriveFormat); 
        Console.WriteLine(
         " Available space to current user:{0, 15} bytes", 
         d.AvailableFreeSpace); 

        Console.WriteLine(
         " Total available space:   {0, 15} bytes", 
         d.TotalFreeSpace); 

        Console.WriteLine(
         " Total size of drive:   {0, 15} bytes ", 
         d.TotalSize); 

       } 
       Console.Read(); 
      } 
     } 
    } 
} 

你想要的DriveInfo類,具體DriveType - 枚舉描述:

DriveType屬性指示驅動器是否是以下任一項:CDRom, 固定,未知,網絡,NoRootDirectory,Ram,可移動或未知。

+0

好的,這是接近可測試的。您忘記提及如何使用路徑中的驅動器號來初始化DriveInfo構造函數。這東西:http://msdn.microsoft.com/en-us/library/system.io.driveinfo.driveinfo.aspx – ahmd0

+0

@ ahmd0我正在使用DriveInfo的靜態方法 - 不需要構造函數 –

+0

@ ahmd0只是使用do a allDrives.First(x => x.Name ==「D」)。DriveType == DriveType.Fixed已經從路徑中提取了驅動器號來測試 –

相關問題