[英]Delete files in temp folder in C#
I am working in Visual Studio 2015 and I am using C#. So I created Windows Form and I added a button named "button1".我在 Visual Studio 2015 中工作,我正在使用 C#。所以我创建了 Windows 表单,并添加了一个名为“button1”的按钮。 What I am trying to do is: when user clicks a button, the content of folder , named ( let´s say ) temp, located in C:/temp, is deleted, but the temp folder still remains .我想做的是:当用户单击一个按钮时,位于 C:/temp 的名为(比方说)temp的文件夹的内容被删除,但temp 文件夹仍然存在。
I have tried to use this:我试过用这个:
private void button1_Click(object sender, EventArgs e)
{
string strCmdText;
strCmdText = "del /q/f/s %TEMP%\* ";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
}
But I was told that this method is useful so I didn't use it anymore.但是听说这个方法有用所以就没用了。 And it also kept throwing an exception: "Unrecognized escape sequence".而且还一直抛出异常:“无法识别的转义序列”。 I was also told I should use System.IO namespace, I also tried to look for tutorials but I didn't find them useful.我还被告知我应该使用 System.IO 命名空间,我也尝试寻找教程但我没有发现它们有用。
If youre looking to delete all files within the temp folder i would do something like this 如果你想删除临时文件夹中的所有文件,我会做这样的事情
var dir = new DirectoryInfo("c:\\temp");
foreach (var file in Directory.GetFiles(dir.ToString()))
{
File.Delete(file);
}
or, if you are looking to delete certain files or types use something like this 或者,如果您要删除某些文件或类型,请使用此类内容
foreach (var file in Directory.GetFiles("c:\\temp", "*.xml", SearchOption.AllDirectories))
{
File.Delete(file);
}
string userName = Environment.UserName; string userName = Environment.UserName;
var dir = new DirectoryInfo("C:\\Users\\"+userName+ "\\AppData\\Local\\Temp");
var d = new DirectoryInfo("C:\\Windows\\Temp");
foreach (var file in Directory.GetFiles(d.ToString()))
{
File.Delete(file);
}
Btw it says Unrecognized Escape Sequence cause you had a slash the wrong way around.顺便说一句,它说 Unrecognized Escape Sequence 因为你用错了斜线。 This is how it should be:这应该是这样的:
string strCmdText;
strCmdText = "del /q/f/s %TEMP%/* ";
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.