1 namespace ClearApps
2 {
3 class Program
4 {
5 static void Main(
string[] args)
6 {
7 //路径
8 string tempPath = System.Environment.GetEnvironmentVariable(
"TEMP");
9 string dirPath = tempPath.Substring(
0, tempPath.LastIndexOf(
@"\") +
1) +
@"Apps\2.0";
10 string logPath=AppDomain.CurrentDomain.BaseDirectory+
"log.txt";
11 string result=
string.Empty;
12 if (ClearRubbish(dirPath,
ref result))
13 {
14 //成功
15 }
16 else
17 {
18 //删除目录操作失败 写入失败原因
19 WriteLog(logPath, result);
20 }
21 }
22
23 /// <summary>
24 /// 删除目录及该目录下的文件
25 /// </summary>
26 /// <param name="dirPath">目录地址</param>
27 /// <param name="strInfo">删除失败报告</param>
28 /// <returns>是否成功</returns>
29 public static bool ClearRubbish(
string dirPath,
ref string strInfo)
30 {
31 //是否清理成功的标志量
32 bool flag =
true;
33 //是否存在该目录
34 if (Directory.Exists(dirPath))
35 {
36 DirectoryInfo dirInfo =
new DirectoryInfo(dirPath);
37 #region//以下2个表达式 把目录的属性只读去掉
38 //dirInfo.Attributes &= ~FileAttributes.ReadOnly;
39 //dirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
40 #endregion
41 try
42 {
43 dirInfo.Delete(
true);
44 }
45 catch (System.UnauthorizedAccessException exRead)
46 {
47 flag =
false;
48 strInfo =
exRead.ToString();
49 }
50 catch (System.IO.DirectoryNotFoundException exDir)
51 {
52 flag =
false;
53 strInfo =
exDir.ToString();
54 }
55 catch (System.IO.IOException exIo)
56 {
57 flag =
false;
58 strInfo =
exIo.ToString();
59 }
60 catch (System.Security.SecurityException exSec)
61 {
62 flag =
false;
63 strInfo =
exSec.ToString();
64 }
65 }
66 else
67 {
68 flag =
false;
69 strInfo =
"该目录不存在!";
70 }
71 return flag;
72 }
73
74 /// <summary>
75 /// 写入日志
76 /// </summary>
77 /// <param name="logPath">日志路径</param>
78 /// <param name="contents">日志内容</param>
79 public static void WriteLog(
string logPath,
string contents)
80 {
81 FileStream fs =
new FileStream(logPath, FileMode.Append, FileAccess.Write);
82 byte[] bytes=Encoding.Default.GetBytes(
string.Format(
"时间:{0}\r\n{1}",DateTime.Now.ToString(),contents));
83 fs.Write(bytes,
0, bytes.Length);
84 fs.Dispose();
85 fs.Close();
86 }
87 }
88 }
转载于:https://www.cnblogs.com/cnlouts/archive/2012/11/29/2795180.html