根据文件名获取目录、后缀名等(C#、C++)

1 篇文章 0 订阅

一、C#根据文件名获取信息

using System;
using System.IO;

namespace ForGetFileName
{
    class Program
    {
        static void Main(string[] args)
        {
            //获取当前运行程序的目录
            string fileDir = Environment.CurrentDirectory;
            Console.WriteLine("当前程序目录:" + fileDir);

            //一个文件目录
            string filePath = @"‪D:\MY FILES\pic\111.bmp";
            string str1 = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //D:\MY FILES\pic
            string str2 = "获取文件的名称含有后缀:" + Path.GetFileName(filePath); //111.bmp
            string str3 = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->111
            string str4 = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //.bmp
            string str5 = "修改得到新的文件名:" + Path.GetDirectoryName(filePath) 
                + "\\" + Path.GetFileNameWithoutExtension(filePath) + "_after.bmp";//‪D:\MY FILES\pic\111_after.bmp
            Console.ReadKey();
        }
    }
}

结果如下:

二、C++根据文件名获取信息

#include "pch.h"
#include <iostream>
#include "string"

using namespace std;

int main()
{
	string filename = "D:\\MY FILES\\pic\\111.bmp";
	//获取文件后缀+.
	string str1 = filename.substr(filename.find_last_of('.'));
	//获取文件后缀不加.
	string str2 = filename.substr(filename.find_last_of('.') + 1);
	//获取文件名+后缀
	string str3 = filename.substr(filename.find_last_of('\\') + 1);
	//获取文件名不加后缀
	string str4 = filename.substr(filename.find_last_of('\\') + 1,
		filename.find_last_of('.') - filename.find_last_of('\\') - 1);
	//获取文件目录
	string str5 = filename.substr(0, filename.find_last_of('\\'));
	cout << "文件名:\t" << filename << endl;
	cout << "文件后缀+.:\t" << str1 << endl;
	cout << "文件后缀不加.:\t" << str2 << endl;
	cout << "文件名+后缀:\t" << str3 << endl;
	cout << "文件名不加后缀:" << str4 << endl;
	cout << "获取文件目录:\t" << str5 << endl;

}

结果如下:

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值