File being used by another process using StreamWriter

c#, streamwriter

Solution

Its recursive.

Because you're calling `Method` again here:

Console.WriteLine(subdir);
sw.Write(subdir);
Method(subdir); // BOOM

Your file is already open. You can't open it for writing again.

Open the file in `Main` once..

static void Main(string[] args) {
    using (StreamWriter sw = new StreamWriter(@"C:\users\"+Environment.UserName+"\desktop\log.txt",true)) {
        Method(@"C:\", sw);
    }
}

Then accept it in your method:

public static void Method(string dir, StreamWriter sw) {

Then when you call it again:

sw.Write(subdir);
Method(subdir, sw); // pass in the streamwriter.

Note though, that you will quickly start chewing up memory. You're recursing through your entire C:\ drive. Maybe test it on a smaller folder?

Problem

My program was practice for me, however, when I try to write all the directories it found, it crashes. I tried the following: - Having it write to a file stream instead of the file itself - using File.Writealllines using a list<> (this worked, only it did the first five and no more) - FileStream.Write(subdir.ToCharArray()) I cannot see why this wouldn't work, what have I done wrong? ``` static void Main(string[] args) { Method(@"C:\"); } static void Method(string dir) { //crash happens here v StreamWriter sw = new StreamWriter(@"C:\users\"+Environment.UserName+"\desktop\log.txt",true); foreach (string subdir in Directory.GetDirectories(dir)) { try { Console.WriteLine(subdir); sw.Write(subdir); Method(subdir); } catch (UnauthorizedAccessException) { Console.WriteLine("Error"); } } sw.Close(); } ```

Original source