在C#中,可以使用Path类的IsPathRooted方法来检查一个字符串是否是合法路径格式。IsPathRooted方法返回一个bool类型的值,指示指定的路径字符串是否包含根路径信息。

以下是一个示例代码:

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        string path1 = @"C:\Program Files\Microsoft";
        string path2 = @"Program Files\Microsoft";
        string path3 = @"..\..\Documents";

        Console.WriteLine(Path.IsPathRooted(path1));  // 输出 True
        Console.WriteLine(Path.IsPathRooted(path2));  // 输出 False
        Console.WriteLine(Path.IsPathRooted(path3));  // 输出 False
    }
}

在上面的示例中,path1是一个合法的绝对路径,因此IsPathRooted方法返回Truepath2path3是相对路径,所以IsPathRooted方法返回False

C# 检查字符串是否是合法路径格式

原文地址: https://www.cveoy.top/t/topic/iG9a 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录