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

