📌  相关文章
📜  检查路径在C#中是否具有文件扩展名

📅  最后修改于: 2021-05-29 14:54:22             🧑  作者: Mango

Path.HasExtension方法用于检查指定路径是否具有文件扩展名。
此方法将开始搜索一个句点(。),然后从路径的末尾开始至少一个字符。如果在遇到DirectorySeparatorCharAltDirectorySeparatorCharVolumeSeparatorChar字符之前找到此模式,则此方法返回true

句法:

public static bool HasExtension (string path);

在此, path是搜索扩展名的指定路径。

返回:此方法如果按照过去的目录分隔符(\\或/)字符或卷分隔符(:)路径包括一个句点(后跟一个或多个字符返回true)。否则为假。

异常:如果路径包含GetInvalidPathChars()中定义的一个或多个无效字符,则此方法将提供ArgumentException

例子:

Input : 
string strPath1 = "C:// myfiles//ref//file1.txt";
string strPath2 = "C:// myfiles//ref//file2";

// checking for the extension
Path.HasExtension(strPath1);
Path.HasExtension(strPath2);

Output :

true
false
// C# program to check whether
// a file have an extension or not
using System;
using System.IO;
  
namespace Geeks {
  
class GFG {
  
    // Main Method
    static void Main(string[] args)
    {
  
        // taking two paths
        string strPath1 = "C:// myfiles// ref// file1.txt";
        string strPath2 = "C:// myfiles// ref// file2";
  
        // checking whether the file 
        // has an extension or not
        if (Path.HasExtension(strPath1))
            Console.WriteLine("{0} have an extension...", strPath1);
        else
            Console.WriteLine("{0} don't have an extension...", strPath1);
  
        // checking whether the file 
        // has an extension or not
        if (Path.HasExtension(strPath2))
            Console.WriteLine("{0} have an extension...", strPath2);
        else
            Console.WriteLine("{0} don't have an extension...", strPath2);
  
        Console.ReadLine();
    }
}
}
输出:
C:// myfiles// ref// file1.txt have an extension...
C:// myfiles// ref// file2 don't have an extension...

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.io.path.hasextension?view=netframework-4.7.2