Search code examples
c#regexfilesavefile-format

How can I replace the same name of a file using regex but in another format?


I am new in programming and not so good about regex. I wish to load / read a csv File and then save in a txt File using the same name of csv File. I will give an example.

D:\Project\File\xxx.csv

After I load this file, I want to get the name "xxx" and save it in a txt file:

D:\Project\File\xxx.txt

Or maybe in another folder, for example:

D:\Project\Specifications\PersonInfo.csv

save to

D:\Project\DataBank\PersonInfo.txt

Solution

  • This can be accomplished in many ways.

    Maybe what you're lacking is knowledge of the System.IO.Path class (MSDN article here).

    For instance changing the extension could be accomplished like so:

    string originalFilePath = @"D:\Project\File\xxx.csv";
    string newFilePath = Path.ChangeExtension(originalFilePath, ".txt");
    

    Note: You need to explicitate the leading dot (".") for the extension.

    Here's some "Path algebra" fun you could combine to create your desired effects:

    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"
    

    Note: Path.Combine knows how to handle extra/missing leading/trailing backslashes.

    For example:

    • 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")

    will all yield the same result: @"D:\MyFolder1\MyFolder2\MyFile.txt"