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

Asked

Viewed 117 times

-1

I need to write a text file from a Dataset in C#, so it will look 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, however, I have several columns in a Dataset and I need to put them in only one line delimiting by semicolon. You could do this without concatenating strings?

I saw some codes where people put "Append()" to concatenate with the delimiter, but I believe it has a way to write the line passing only the Dataset and a delimiter, some library, anything that does it in a more simplified way, that leaves code cleaner and more flexible to different layouts.

If this cannot be done with text files (*.txt), it would be possible to do this with CSV?

  • is and isn’t, depends on the definition, or what you want, but you need to know why it needs to be like this, what’s wrong with doing it this way? This has nothing to do with files or your type.

  • Need it because I want something simple, clean.

  • It’s clear you don’t need it. Simpler and cleaner than that? I find it hard. You can lose performance?

  • I don’t know about the performance, because I didn’t test in other ways than with Loop. Only I see it like this, man, I’m the one programming, so at least who needs to know if I need it or not, I’m myself kkkk. The question will remain open because I believe it has something similar to what I want, thank you for your attention.

1 answer

1


Well, an alternative if you want to "avoid loopings" visible in your code is to use the string. Join(String, String[]). But under the table he will do more operations than those already existing in his code snippet.

What he will do is a loop in his string[], adding a string separation between the elements (which in your case is a line break) and concatenate everything into 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);
}
  • Thanks for the help, I ended up using the Loop even, I managed to do in a simple way taking only 4 lines where the file is structured according to a layout, it was very good.

  • 1

    @L.Gustavo It would be interesting for you to post your solution as answer then.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.