【问题标题】:How to check if path refers to a local file object?如何检查路径是否引用本地文件对象?
【发布时间】:2013-10-17 07:06:34
【问题描述】:

我试图找出某个任意路径是指本地文件系统对象还是位于网络共享或可移动驱动器上的路径。 .NET 中有没有办法做到这一点?

PS。换句话说,如果我有硬盘 C: 和 D: 并且驱动器 E: 是 DVD 驱动器或 USB 闪存驱动器,那么:

以下路径将是本地的:

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

以下路径不会:

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

【问题讨论】:

标签: c# .net filesystems


【解决方案1】:
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、可移动或未知。

【讨论】:

  • 好的,这已经接近可测试了。您忘记提及如何使用路径中的驱动器号初始化 DriveInfo 构造函数。这玩意儿:msdn.microsoft.com/en-us/library/…
  • @ahmd0 我正在使用 DriveInfo 的静态方法 - 不需要构造函数
  • @ahmd0 只需使用 allDrives.First(x=>x.Name == "D").DriveType == DriveType.Fixed 从路径中提取驱动器号进行测试
  • @Jacee:我刚刚尝试过:DriveInfo di = new DriveInfo(@"D:\My Files\File.exe");,它成功了。我是否使用了未记录的东西?
  • @ahmd0 不,DriveInfo 构造函数接受路径,因此您可以以这种方式为特定路径加载信息
猜你喜欢
  • 2022-01-19
  • 1970-01-01
  • 1970-01-01
  • 2016-05-14
  • 1970-01-01
  • 1970-01-01
  • 2014-02-20
  • 2021-03-08
  • 2014-03-09
相关资源
最近更新 更多