首页 > 解决方案 > Streamwriter 不会覆盖文件

问题描述

我有使用 StreamWriter 创建 powershell 脚本的简单功能。

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)");
            }
        }

    }

问题是当我使用“FileMode.Create”时它应该覆盖现有文件。

但如果文件已经存在,它不会覆盖它。有谁知道什么可能导致问题?

感谢您的回答。

标签: c#streamwriter

解决方案


因为如果文件存在,您明确告诉代码什么都不做:

if (!File.Exists(path))

在这种StreamWriter情况下,甚至永远不会在运行时创建。如果您不想要这种情况,请将其删除。

(旁注:这是使用调试器重要性的一个很好的例子。在调试器中单步执行此代码时,您会立即注意到没有输入条件并且大部分代码根本没有执行。)


推荐阅读