c# - 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
情况下,甚至永远不会在运行时创建。如果您不想要这种情况,请将其删除。
(旁注:这是使用调试器重要性的一个很好的例子。在调试器中单步执行此代码时,您会立即注意到没有输入条件并且大部分代码根本没有执行。)
推荐阅读
- terraform - 发生崩溃时 remote-exec 脚本位于何处?
- reactjs - Auth0 重定向到错误的地址
- ios - 照片选择器错误 - 使用时与插件的连接中断
- javascript - 在 html 中使用单选按钮添加价格
- javascript - 为什么我需要两次点击两次才能触发onclick事件 - tictactoe
- c# - Xamarin.Forms:在 C# 中绑定到整个 BindingConext(不是 XAML)
- javascript - 如何使下拉菜单恰好出现在 Material-UI 中的栏下方?
- api - 空手道:是否可以从场景大纲中匹配 json
- python - 如何清理 matplotlib 中的 x 轴值?
- python - 如何将列中的所有值从数千转换为数十亿?使用熊猫