A guy at the company I work for needed a small application that would combine multiple text files into one, larger text file.
I wrote a console application for this. it seems pretty efficient, but I was wondering if there would be an even more efficient way of doing this.
It has 2 important functions, one that gets the files from a folder, where string input is the folder location:
static string[] getFiles(string input)
{
DirectoryInfo dinfo = new DirectoryInfo(@input);
FileInfo[] files = dinfo.GetFiles("*.txt");
List<string> list = new List<string>();
foreach(FileInfo file in files)
{
list.Add(input + @"\" + file.Name);
}
string[] arr = list.ToArray();
return arr;
}
And of course the function that combines the files together, its input are the name of the file (string newName) and an array with the names of the files found in the folder by getFiles() (string[] files):
static void writeDump(string newName, string[] files)
{
if (!File.Exists(newName))
{
using (StreamWriter sw = File.CreateText(newName))
{
for (int i = 0; i < files.Length; i++)
{
using (StreamReader sr = File.OpenText(files[i]))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
sw.WriteLine(s);
}
}
}
}
} else
{
Console.Clear();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("File already exists");
start(); //start is called from the main function
}
}
And because start(); might be confusing, I'll also add the main function here:
static void Main(string[] args)
{
start();
}
How efficient is this and could it be more efficient?
catfrom the console? \$\endgroup\$cat? \$\endgroup\$cat path/to/files/*.txt > my_output_file.txtinstead of writing a program. But writing programs is fun/learning ;-) \$\endgroup\$cat. I'm not trying to discourage you, but I don't think you should get the idea that using C# is going to result in way less time consuming operations as compared to basic shell commands. Unless you're addressing some kind of edge case (4 files that concatenate in less than a second probably doesn't qualify). \$\endgroup\$