I am using the following code to read and combine number of texts in one string:
foreach (string path in filePaths)
{
StreamReader singfile = new StreamReader(path);
string file_text = singfile.ReadToEnd();
combinetexts += file_text + "\n";
fs.Close();
}
and as I know, the string combinetexts will copy n times as much as the number of filepaths. is it possible the to do that orcedure using string builder ? I tried but it doesn’t.
thanks in advance.
Here’s a short LINQ way of doing it:
Or with C# 4 (which has better handling of type inference wrt method group conversions):
If you’re using .NET 3.5 you’ll need to create an array of the strings, as
string.Joindidn’t have as many overloads then:This has the disadvantage of reading all of all the files before performing the concatenation, admittedly – but it’s still better than the repeated concatenation in the original code. It might also be more efficient than using
StringBuilder– it depends on thestring.Joinimplementation.See my article on
StringBuilderfor why the original code is really inefficient.EDIT: Note that this does not include a trailing
\nat the end. If you really want to add that, you can 🙂