![](/img/trans.png)
[英]How can i replace in console application image file format with the same file name but different format?
[英]How can I replace the same name of a file using regex but in another format?
我是編程新手,對正則表達式不太滿意。 我希望加載/讀取一個csv文件,然后使用與csv文件相同的名稱保存在txt文件中。 我舉一個例子。
D:\Project\File\xxx.csv
加載此文件后,我想獲取名稱“ xxx”並將其保存在txt文件中:
D:\Project\File\xxx.txt
或者也許在另一個文件夾中,例如:
D:\Project\Specifications\PersonInfo.csv
存到
D:\Project\DataBank\PersonInfo.txt
您不需要正則表達式。
您可以使用Path.GetFileName或Path.GetFileNameWithoutExtension :
string fileName = Path.GetFileNameWithoutExtension("D:\Project\Specifications\PersonInfo.csv");
您不需要正則表達式,因為.NET提供了System.IO.Path
類來專門處理文件名操作。
例如,要將.csv
替換為.txt
,可以使用以下調用:
var csvPath = @"D:\Project\File\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(csvPath)
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
您使用類似的技巧來替換文件路徑的其他部分。 這是更改頂部目錄名稱的方法:
var csvPath = @"D:\Project\Specifications\xxx.csv";
var txtPath = Path.Combine(
Path.GetDirectoryName(Path.GetDirectoryName(csvPath))
, "DataBank"
, Path.GetFileNameWithoutExtension(csvPath)+".txt"
);
這可以通過許多方式來實現。
也許您缺少的是System.IO.Path
類的知識( 此處是MSDN文章 )。
例如,更改擴展名可以像這樣完成:
string originalFilePath = @"D:\Project\File\xxx.csv";
string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
注意 :您需要明確顯示擴展名的前導點(“。”)。
您可以結合一些“路徑代數”的樂趣來創建所需的效果:
string originalFilePath = @"D:\Project\File\xxx.csv";
string thePath = Path.GetDirectoryName(originalFilePath);
// will be @"D:\Project\File"
string filename = Path.GetFileName(originalFilePath);
// will be "xxx.csv"
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(originalFilePath);
// will be "xxx"
string recombinedFilePath = Path.Combine( @"D:\OtherFolder", "somethingElse.txt" );
// will be @"D:\OtherFolder\somethingElse.txt"
注意 : Path.Combine
知道如何處理多余的/缺少的前導/尾隨反斜杠。
例如:
Path.Combine(@"D:\\MyFolder1", @"MyFolder2\\MyFile.txt")
Path.Combine(@"D:\\MyFolder1\\", @"MyFolder2\\MyFile.txt")
Path.Combine(@"D:\\MyFolder1", @"\\MyFolder2\\MyFile.txt")
Path.Combine(@"D:\\MyFolder1\\", @"\\MyFolder2\\MyFile.txt")
都會產生相同的結果: @"D:\\MyFolder1\\MyFolder2\\MyFile.txt"
如果您要為此使用正則表達式,則此正則表達式將獲得您想要的零件:
([^\\]+)\.[^.\\]+$
第一組(在括號中)與一個或多個字符(盡可能多)匹配,而不是反斜杠。 然后需要有一個文字點。 然后是一個或多個(盡可能多的)不是點或反斜杠的字符,然后是字符串的結尾。 該小組捕獲了需要的部分。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.