如何检查路径是否指向本地文件对象?

3

我正在尝试确定一些任意路径是否指向本地文件系统对象,还是位于网络共享或可移动驱动器上的对象。在.NET中有没有办法做到这一点?

PS. 换句话说,如果我有C:和D:硬盘,E:是DVD驱动器或USB闪存驱动器,则:

以下路径将是本地路径:

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

以下路径将不会被包含:
E:\File on usb stick.txt
\\computer\file.ext

DriveInfo类将告诉您驱动器类型,根据驱动器字母。 - PhoenixReborn
这个问题似乎已经在这个帖子中得到了回答。 - Brennan
1个回答

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、Fixed、Unknown、Network、NoRootDirectory、Ram、Removable或Unknown。


好的,这已经接近可测试的程度了。你忘记提到如何使用路径中的驱动器字母初始化DriveInfo构造函数。这个东西:http://msdn.microsoft.com/en-us/library/system.io.driveinfo.driveinfo.aspx - ahmd0
@ahmd0 我正在使用 DriveInfo 的静态方法 - 不需要构造函数 - Jaycee
@ahmd0 只需要使用 do a allDrives.First(x=>x.Name == "D").DriveType == DriveType.Fixed,从路径中提取驱动器字母进行测试。 - Jaycee
@Jacee:我刚刚尝试了这样的写法:DriveInfo di = new DriveInfo(@"D:\My Files\File.exe");,它起作用了。我是不是在使用一些未记录的东西? - ahmd0
@ahmd0 不,DriveInfo 构造函数接受一个路径,因此你可以通过指定路径来加载相关信息。 - Jaycee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接