Click here to Skip to main content
15,849,129 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to make a program that allows the user to export data to txt, however I want first to ask user what is the path to create the txt. However I'm not getting right the replace function, I doing adding a variable.
Sorry if it's a sily question.

What I have tried:

string path = @"##Insert##\export.txt";

        Console.WriteLine("Insert the path to export txt: ");
        string temp = Console.ReadLine();
        path = path.Replace($"##Insert##", "{temp}");
Updated 21-Aug-18 9:52am

I mean what try will try to do, create a file or a directory? and also the txt will be created where if in the example above it's not being asked to user the path?
Share this answer
Why are you even using a Replace? You should be getting the folder path from the user, making sure it exists or you create the path, then you append the filename to the path using Path.Combine().
string folderPath = Console.ReadLine();
if (!Directory.Exists(path)
    // The directory path doesn't exist. Try to create it
    // or ask the user if it should be created, then create it
    // if told to.
    catch (...)
        // The path couldn't be created for some reason...

folderPath = Path.Combine(folderPath, "export.txt");
Share this answer
Leonardo Guimarães 21-Aug-18 6:25am    
I get what you said that I have to check if directory exists, but I'm still confused about the try catch statement, what does try even do? Also what is assigned on the path variable? cause you're checking if it exists, but it should be coming as an input. Sorry if I have'nt been clear, I'm really confused, lol
Dave Kreskowiak 21-Aug-18 11:52am    
You really need to learn the basics of C#. try/catch/finally blocks are used for exception handling. If code in the try block fails for some reason, you have the opportunity to do something in response to it.
I do not think that the Replace method uses format strings, as they have no meaning in this context. See String.Replace Method (System) | Microsoft Docs[^].
Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900