获取给定文件扩展名的 C# 程序
DirectoryInfo 类提供不同类型的方法和属性,用于对目录和子目录执行操作,如创建、移动等。此类具有Extension属性,用于从给定文件名中查找扩展部分,其中包括文件全名中的点格式。例如,如果文件名为 c:\gfg.txt,则该属性将返回“.txt”。
句法:
public string Extension { get; }
返回:它将返回一个带有当前文件点格式扩展名的字符串。即使它是完整的文件名或空字符串,或者没有可用的扩展名。
例子:
C#
// C# program to find the extension of a given File
using System;
using System.IO;
class GFG{
static void Main()
{
// Specify text file
DirectoryInfo extension = new DirectoryInfo("my_data.txt");
// Get the extension of the File
// Using Extension property
Console.WriteLine("File extension : " + extension.Extension);
// Specify pdf file
DirectoryInfo extension1 = new DirectoryInfo("my_data.pdf");
// Get the extension of the File
// Using Extension property
Console.WriteLine("File extension : " + extension1.Extension);
// Specify the file which has no extension
DirectoryInfo extension2 = new DirectoryInfo("gfg");
// Get the extension of the File
// Using Extension property
Console.WriteLine("File extension : " + extension2.Extension);
// Specify the file which has multiple dots
DirectoryInfo extension3 = new DirectoryInfo("gfg.gg.txt");
// Get the extension of the File
// Using Extension property
Console.WriteLine("File extension : " + extension3.Extension);
}
}
输出:
File extension : .txt
File extension : .pdf
File extension :
File extension : .txt