Writing a line in text file without using repeat instruction, is it possible?

-1

I need to write a text file from a DataSet in C #, so something like:

string[] lines = {"First line", "Second line", "Third Line"}
using(StreamWriter outputFile = new StreamWriter(docPath)){
   foreach(string line in lines){
       outputFile.WriteLine(line);
   }
}
So far so good though, I have several columns in a DataSet and I need to put them in just one line delimiting by a semicolon. Would you like to do this without concatenating strings?

I've seen some code where people put "Append ()" to concatenate with the delimiter, but I believe I have a way to write the line passing just the DataSet and a delimiter, some library, anything that does it more simplified, which makes the code cleaner and more flexible to different layouts.

If you can not do this with text files (* .txt), would it be possible to do with CSV?

    
asked by anonymous 09.07.2018 / 04:14

1 answer

1

Well, an alternative if you want to "avoid looping" visible in your code is to use string.Join (String, String []) . But underneath the wipes he will do more operations than the ones already in his code snippet.

What it does is a loop in its string[] , adding a string of separation between the elements (which in its case is a line break) and concatenate everything in a single string .

string[] lines = { "First line", "Second line", "Third Line" };

using (StreamWriter outputFile = new StreamWriter(docPath))
{
    string text = string.Join("\r\n", lines);
    outputFile.Write(text);
}
    
09.07.2018 / 14:48