Streamwriter 不会覆盖文件
Streamwriter wont overwrite file
我有使用 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" 时它应该覆盖现有文件。
但是如果文件已经存在,它不会覆盖它。有谁知道什么会导致问题?
感谢您的回答。
因为您明确告诉代码如果文件存在则什么也不做:
if (!File.Exists(path))
在这种情况下,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" 时它应该覆盖现有文件。
但是如果文件已经存在,它不会覆盖它。有谁知道什么会导致问题?
感谢您的回答。
因为您明确告诉代码如果文件存在则什么也不做:
if (!File.Exists(path))
在这种情况下,StreamWriter
甚至不会在运行时创建。如果您不想要该条件,请将其删除。
(旁注:这是使用调试器重要性的很好示例。在调试器中逐步执行此代码时,您会立即 注意没有输入条件,大部分代码根本没有执行。)