【问题标题】:How to run the delete command via Process?如何通过 Process 运行删除命令?
【发布时间】:2011-06-24 15:06:22
【问题描述】:
这个不行,找不到del.exe...
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = "del.exe";
p.StartInfo.Arguments = "*.bak";
p.Start();
p.Close();
【问题讨论】:
标签:
c#
class
process
class-library
【解决方案1】:
你做错了。您应该改用File.Delete method。
示例代码:
string sourceDir = @"C:\Backups"; // change this to the location of the files
string[] bakList = Directory.GetFiles(sourceDir, "*.bak");
try
{
foreach (string f in bakList)
{
File.Delete(f);
}
}
catch (IOException ioex)
{
// failed to delete because the file is in use
}
catch (UnauthorizedAccessException uaex)
{
// failed to delete because file is read-only,
// or user doesn't have permission
}
【讨论】:
-
-
@001:使用try-catch block。我已经用一个示例更新了我的答案,该示例捕获了您最有可能遇到的两个异常(它们列在我在答案中链接到的文档页面上)。您可以在catch 块中执行 某些操作,或者如图所示将其留空,这将简单地忽略错误。