Is there a memory efficient way to use 'using' within a recursive function when e.g. writing lines to a file?
I read C# 'using' block inside a loop and it mentioned that you don't want to put a using statement inside a for loop unless you have to. (makes sense, one doesn't want multiple instances of 'using' if one doesn't need them). So in the case of a for loop if you can put it outside, you do.
But here, I have a recursive function. So the 'using' statement is going to run multiple times even if I put it outside of a for.
So what is a good or proper way of placing the 'using' statement?
I don't know if I should avoid 'using', and declare the StreamWriter object, StreamWriter writetext
before the method call and dispose of it after with writetext.Dispose()
. Or maybe there is a more conventional way with 'using'. Maybe wrapping the 'main' call DirSearch_basic_writetofile("c:\\aaa");
with a 'try' and putting the Dispose line in a finally. And avoiding 'using' then. That's just a thought.
// requires directory c:\texts
File.Delete(@"c:\texts\filelist.txt");
// list files and subdirectories of c:\aaa and write them to file "c:\texts\filelist.txt"
DirSearch_basic_writetofile("c:\\aaa");
// recursive function that lists files and directories and subdirectories,in given directory
static void DirSearch_basic_writetofile(string sDir)
{
Console.WriteLine("DirSearch(" + sDir + ")");
Console.WriteLine(sDir+@"\");
try
{
using (StreamWriter writetext = new StreamWriter("c:\\texts\\filelist.txt",true))
{
writetext.WriteLine("DirSearch(" + sDir + ")");
writetext.WriteLine(sDir);
foreach (string f in Directory.GetFiles(sDir))
{
Console.WriteLine(f);
writetext.WriteLine(f);
}
}
foreach (string d in Directory.GetDirectories(sDir))
{
DirSearch_basic_writetofile(d);
}
}
catch (System.Exception excpt)
{
Console.WriteLine(excpt.Message);
}
}