C#怎么实现修改文件的创建时间以及最后更新时间为指定的时间
powershell实现修改文件的创建时间以及最后更新时间
接到一个需求:
要用最新的程序重新打包一份以前的项目安装程序 但要求把程序包内的文件的创建时间修改为以前的一个时间点 据说是为了应付上面审查 大概意思是相关人员检查时防止被查到文件时间太新,虽然觉得有点欲盖弥彰的意思 但毕竟是工作 以下是实现修改的文件创建时间以及最后更新时间的 方法
需要先添加powershell链接库引用
首先引用 System.Management.Automation
应该是再 C:\ Program Files \ Reference Assemblies \ Microsoft \ WindowsPowerShell \ v1.0 目录下
///运行脚本
private static string RunScript(string scriptText)
{
Runspace runspace = RunspaceFactory.CreateRunspace();
runspace.Open();
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(scriptText);
pipeline.Commands.Add("Out-String");
Collection<PSObject> results = pipeline.Invoke();
runspace.Close();
StringBuilder stringBuilder = new StringBuilder();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
return stringBuilder.ToString();
}
调用例子
//修改文件最后更新时间
string cmd = $"Set-ItemProperty -Path {file.FullName} -Name LastWriteTime -Value \"2020-12-15 11:33:44\"";
string xx= RunScript(cmd);
//修改文件创建时间
cmd = $"Set-ItemProperty -Path {file.FullName} -Name CreationTime -Value \"2020-12-15 11:33:44\"";
xx = RunScript(cmd);