C#如何獲取文件全路徑、目錄、擴展名、文件名稱
更新時間:2023年07月13日 09:18:46 作者:熊思宇
這篇文章主要介紹了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(); } } }
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
C#設置WinForm中DataGrid列的方法(列寬/列標題等)
這篇文章主要介紹了C#設置WinForm中DataGrid列的方法,包括列寬、列標題等部分,并分析了其中相關的操作技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-07-07Unity打開淘寶app并跳轉到商品頁面功能的實現(xiàn)方法
這篇文章主要給大家介紹了關于如何利用Unity打開淘寶app并跳轉到商品頁面功能的相關資料,這個功能目前在網(wǎng)上找不到相關的解決方法,所以自己寫了出來,需要的朋友可以參考下2021-07-07