一、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;
}
结果如下: