-1

I'm trying to create a scenario where you have a text box, you enter the name of something, press enter and do that as many times as you want. Then when you press 'generate' it takes all the names you entered in the box total and puts them in a document with the structure of:

{"item1", "item2", "item3"} and so on depending on how many items you put in (with the possibility of putting 0 things in)

I've already know how to print the document, but I'm confused on how to print the list of strings you create to the document.

Tamir Vered
  • 10,187
  • 5
  • 45
  • 57
FirstOrderKylo
  • 99
  • 3
  • 12

2 Answers2

1

You can do this like so:

string[] original = {"one", "two", "three", "four", "five"};

string result = "{\"" + string.Join("\", \"", original) + "\"}";

Console.WriteLine(result); // Prints {"one", "two", "three", "four", "five"}

You will end up with the string you want in result, and you can write it to a file as desired.

A simple way to write text to a file is like this:

File.WriteAllText("File path goes here", result);
Matthew Watson
  • 104,400
  • 10
  • 158
  • 276
0

At the time of writing this answer, the question is a bit ambiguous. I assume you already have a list with the contents, and simply want to write it to a file.

You can't directly print a list to the document, you first need to build a string from the list parts, and then write it:

const string quote = "\"";
const string separator = ", ";
// your list from user input
List<string> items = new List<string> {
    "item1",
    "item2",
    "item3"
};

string result = "";
for (int i = 0; i < items.Count; i++) {
    // append the current item, surronded by quotes.
    result += quote + items[i] + quote;

    // only add comma if it's not the last item
    if (i < items.Count - 1) {
        result += separator;
    }
}
result = "{" + result + "}";

File.WriteAllText("yourfile.txt", result);

But in such cases, a StringBuilder might be more efficient than that much concatenation.