-2

I have easy function which creates powershell script using StreamWriter.

public static void CreateDomainScript(string domain, string username, string pcname)
    {
        string path = @"C:\Windows\Temp\JoinDomain.ps1";
        if (!File.Exists(path))
        {
            using (StreamWriter sw = new StreamWriter(File.Open(path, FileMode.Create), Encoding.Unicode))
            {
                sw.WriteLine("$MaxAttempts = 0");
                sw.WriteLine("do {");
                sw.WriteLine("    Add-Computer -DomainName " + domain + " -Credential " + username + " -NewName " + pcname);
                sw.WriteLine("    $success = $?");
                sw.WriteLine("    if (-not $success) {");
                sw.WriteLine("        $MaxAttempts++");
                sw.WriteLine("        Write-Host \"Pokus\" $MaxAttempts \"z 5\" ");
                sw.WriteLine("        if($MaxAttempts -eq \"4\")");
                sw.WriteLine("        {");
                sw.WriteLine("        Write-Host \"Mas posledni pokus, snaz se :-)\"");
                sw.WriteLine("        }");
                sw.WriteLine("        if ($MaxAttempts -eq \"5\")");
                sw.WriteLine("        {");
                sw.WriteLine("        Write-Host \"Detekovana chyba mezi klavesnici a zidli. Vypni konzoli a pripoj to do domeny rucne\"");
                sw.WriteLine("        }");
                sw.WriteLine("       }");
                sw.WriteLine("    else");
                sw.WriteLine("    { ");
                sw.WriteLine("    Write-Host \"Spravne heslo.Pripojeni do domeny uspesne. Vypni konzoli test32\" ");
                sw.WriteLine("    }");
                sw.WriteLine("} until ($success -or $MaxAttempts -ge 5)");
            }
        }

    }

Problem is it should overwrite the existing file when im using "FileMode.Create".

But if the file already exists it wont override it. Does anyone know what could cause a problem?

Thanks for answers.

Johny Corbie
  • 63
  • 10
  • **[Navigating through Code using the Step Debugger](https://msdn.microsoft.com/en-us/library/y740d9d3.aspx)** – Ňɏssa Pøngjǣrdenlarp Sep 08 '19 at 14:57
  • The `FileStream` returned by `File.Open` needs to be disposed. You're not calling the `StreamWriter` constructor overload that takes the file path so it doesn't create, and therefore own, the stream object. – madreflection Sep 08 '19 at 17:27

1 Answers1

3

Because you're explicitly telling the code to do nothing if the file exists:

if (!File.Exists(path))

The StreamWriter is never even being created at runtime in this case. If you don't want that condition, remove it.

(Side note: This is a great example of the importance of using a debugger. When stepping through this code in a debugger you would immediately notice that the condition is not being entered and the majority of the code isn't executing at all.)

David
  • 208,112
  • 36
  • 198
  • 279