C#如何获取文件全路径、目录、扩展名、文件名称

Gella ·
更新时间:2024-09-20
· 1144 次阅读

目录

C#获取文件全路径、目录、扩展名、文件名称

C#批量修改文件后缀

总结

C#获取文件全路径、目录、扩展名、文件名称

代码:

using System; using System.IO; class Program { static void Main(string[] args) { //获取当前运行程序的目录 string fileDir = Environment.CurrentDirectory; Console.WriteLine("当前程序目录:" + fileDir); //一个文件目录 string filePath = "C:\\JiYF\\BenXH\\BenXHCMS.xml"; Console.WriteLine("该文件的目录:" + filePath); string str = "获取文件的全路径:" + Path.GetFullPath(filePath); //-->C:\JiYF\BenXH\BenXHCMS.xml Console.WriteLine(str); str = "获取文件所在的目录:" + Path.GetDirectoryName(filePath); //-->C:\JiYF\BenXH Console.WriteLine(str); str = "获取文件的名称含有后缀:" + Path.GetFileName(filePath); //-->BenXHCMS.xml Console.WriteLine(str); str = "获取文件的名称没有后缀:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS Console.WriteLine(str); str = "获取路径的后缀扩展名称:" + Path.GetExtension(filePath); //-->.xml Console.WriteLine(str); str = "获取路径的根目录:" + Path.GetPathRoot(filePath); //-->C:\ Console.WriteLine(str); Console.ReadKey(); } } C#批量修改文件后缀

一个文件夹里有多个文件,如果想把它们的后缀全部修改,在C#里写几行代码即可

直接附上代码:

using System; using System.IO; using Microsoft.VisualBasic.Devices; namespace ChangeSuffix { class Program { static public string path = @"E:\files"; static void Main(string[] args) { Computer myComputer = new Computer(); DirectoryInfo dir = new DirectoryInfo(path); FileInfo[] files = dir.GetFiles(); foreach (var file in files) { string newName = file.Name.Replace(".xlsx", ".txt"); //.xlsx修改成.txt if(newName != file.Name) myComputer.FileSystem.RenameFile(file.FullName, newName); } Console.ReadLine(); } } } 总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持软件开发网。



C# 扩展 扩展名

需要 登录 后方可回复, 如果你还没有账号请 注册新账号