C#如何獲取文件全路徑、目錄、擴(kuò)展名、文件名稱
更新時(shí)間:2023年07月13日 09:18:46 作者:熊思宇
這篇文章主要介紹了C#如何獲取文件全路徑、目錄、擴(kuò)展名、文件名稱問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
C#獲取文件全路徑、目錄、擴(kuò)展名、文件名稱
代碼:
using System; using System.IO; class Program { static void Main(string[] args) { //獲取當(dāng)前運(yùn)行程序的目錄 string fileDir = Environment.CurrentDirectory; Console.WriteLine("當(dāng)前程序目錄:" + fileDir); //一個(gè)文件目錄 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 = "獲取文件的名稱沒(méi)有后綴:" + Path.GetFileNameWithoutExtension(filePath); //-->BenXHCMS Console.WriteLine(str); str = "獲取路徑的后綴擴(kuò)展名稱:" + Path.GetExtension(filePath); //-->.xml Console.WriteLine(str); str = "獲取路徑的根目錄:" + Path.GetPathRoot(filePath); //-->C:\ Console.WriteLine(str); Console.ReadKey(); } }
C#批量修改文件后綴
一個(gè)文件夾里有多個(gè)文件,如果想把它們的后綴全部修改,在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(); } } }
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
C#設(shè)置WinForm中DataGrid列的方法(列寬/列標(biāo)題等)
這篇文章主要介紹了C#設(shè)置WinForm中DataGrid列的方法,包括列寬、列標(biāo)題等部分,并分析了其中相關(guān)的操作技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07Unity打開(kāi)淘寶app并跳轉(zhuǎn)到商品頁(yè)面功能的實(shí)現(xiàn)方法
這篇文章主要給大家介紹了關(guān)于如何利用Unity打開(kāi)淘寶app并跳轉(zhuǎn)到商品頁(yè)面功能的相關(guān)資料,這個(gè)功能目前在網(wǎng)上找不到相關(guān)的解決方法,所以自己寫了出來(lái),需要的朋友可以參考下2021-07-07C#中將DataTable轉(zhuǎn)化成List<T>的方法解析
大家應(yīng)該都知道在.net項(xiàng)目中使用到DataTable和List<T>集合的地方較多,有的時(shí)候需要將DataTable轉(zhuǎn)化成List<T>,那么改如何轉(zhuǎn)化呢?下面通過(guò)這篇文章來(lái)一起學(xué)習(xí)下吧,本文中給出了詳細(xì)的示例代碼,相信對(duì)大家的理解和學(xué)習(xí)具有一定的參考借鑒價(jià)值。2016-12-12