编程小白的第一篇博客*-*
分享C#提取后缀名以及提取某一类型后缀名个数的方法,提取的关键是截取路径‘.’到路径末尾的字符,较容易实现。如有错误,还望指正。
注:使用的是Visual Studio 2012。
代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 截取后缀名
{
class Program
{
static void Main(string[] args)
{
//情况一:已知文件,提取文件路径的后缀名
string path = @"D:\新建文件夹\新建 PPTX 演示文稿.pptx";//注意:文件路径前要加上@,否则因为歧义而报错
string hzm = path.Substring(path.IndexOf('.') + 1, path.Length - (path.IndexOf('.') + 1));//从.后开始截取,截止到文件路径末尾
Console.WriteLine(path);
Console.WriteLine(hzm);
Console.WriteLine();
//调用情况二的 Getcount
Program pro = new Program();
pro.Getcount(@"D:\新建文件夹", "txt");//给Getcount赋实参,即pro.Getcount()的括号内输入实际文件夹的路径和所提取类型的后缀名名称
}
//情况二:已知文件夹路径,提取文件夹里所有文件的后缀名并计算文件夹某一类型文件的个数
//定义一个返回计算个数的函数
public string[] Getcount(string filespath, string type)//Getcount函数返回值是 string[],filespath和type为形参
{
int count = 0;
string[] allfilePath = System.IO.Directory.GetFiles(filespath);//获取文件夹路径
//Console.WriteLine("文件路径如下:");
foreach (var item in allfilePath)
{
Console.WriteLine(item);
}
for (int i = 0; i < allfilePath.Length; i++)
{
string hzms = allfilePath[i].Substring(allfilePath[i].IndexOf('.') + 1, allfilePath[i].Length - (allfilePath[i].IndexOf('.') + 1));
Console.WriteLine(hzms);//和情况一截取原理一致
if (hzms == type)
{
count++;
}
}
Console.WriteLine("{0}的个数有{1}个", type, count);
return allfilePath;//设置返回值
}
}
}
运行结果如下: