首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

从路径字符串或FileInfo获取驱动器号

从路径字符串或FileInfo获取驱动器号是一种常见的操作,它可以帮助我们快速地获取文件或目录所在的驱动器。以下是一个简单的示例,说明如何从路径字符串或FileInfo获取驱动器号。

代码语言:csharp
复制
using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string path = @"C:\Users\Public\Documents\MyFile.txt";
        string driveLetter = GetDriveLetterFromPath(path);
        Console.WriteLine($"驱动器号:{driveLetter}");

        FileInfo fileInfo = new FileInfo(path);
        driveLetter = GetDriveLetterFromFileInfo(fileInfo);
        Console.WriteLine($"驱动器号:{driveLetter}");
    }

    static string GetDriveLetterFromPath(string path)
    {
        string driveLetter = string.Empty;
        if (Path.IsPathRooted(path))
        {
            driveLetter = Path.GetPathRoot(path);
        }
        return driveLetter;
    }

    static string GetDriveLetterFromFileInfo(FileInfo fileInfo)
    {
        string driveLetter = string.Empty;
        if (fileInfo.FullName.Length >= 2)
        {
            driveLetter = fileInfo.FullName.Substring(0, 2);
        }
        return driveLetter;
    }
}

在这个示例中,我们定义了两个方法:GetDriveLetterFromPathGetDriveLetterFromFileInfoGetDriveLetterFromPath方法接受一个路径字符串作为参数,使用Path.GetPathRoot方法获取驱动器号。GetDriveLetterFromFileInfo方法接受一个FileInfo对象作为参数,直接从FullName属性中获取驱动器号。

Main方法中,我们首先定义了一个路径字符串,然后调用GetDriveLetterFromPath方法获取驱动器号,并将其输出到控制台。接着,我们使用路径字符串创建了一个FileInfo对象,并调用GetDriveLetterFromFileInfo方法获取驱动器号,并将其输出到控制台。

这个示例演示了如何从路径字符串或FileInfo对象获取驱动器号,并且可以根据实际需要进行扩展和修改。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的视频

领券