原文地址:清理Visual Studio 2017旧版本离线安装文件
说明
Visual Studio 2017内容庞大,如果在线安装相当耗时,因此多数情况下采用离线安装方式。比如用下面的命令:
vs_enterprise.exe --layout F:\Dev\VisualStudio\VS2017Ent --lang zh-CN
上面的命令将安装包下载到F:\Dev\VisualStudio\VS2017Ent
目录下,用户可以使用本地文件离线安装 Visual Studio 2017。但是,当再次执行上面命令更新离线安装包后,旧版本的安装包不会自动删除,导致离线安装包越来越庞大,存在大量无用安装文件。
- 下面的代码用来清理旧版本离线安装文件。
- C#语言。
- 程序为控制台应用程序。
- Visual Studio 2017 测试通过。
具体代码
文件名:DelLegacyFolder.cs
using System;
using System.Collections.Generic;
using System.IO;
namespace SampleCode
{
class DelLegacyFolder
{
static void Main(string[] args)
{
try
{
//string dirPath = @"F:\Dev\VisualStudio\VS2017Ent";
string dirPath = @".";
List<string> dirs = new List<string>(Directory.EnumerateDirectories(dirPath));
List<string> olderFolder = new List<string>();
//不自行排序,使用系统自己的排序方式
//dirs.Sort();
int count = 0;
for (int i = 0; i < dirs.Count - 1; i++)
{
string[] OlderFolderName = dirs[i].Split(',');
string[] NewerFolderName = dirs[i + 1].Split(',');
if ((OlderFolderName[0] == NewerFolderName[0])
&& (OlderFolderName[1] != NewerFolderName[1])
&& (OlderFolderName.Length == NewerFolderName.Length))
{
bool ifNeedOperation = false;
switch (OlderFolderName.Length)
{
case 2:
ifNeedOperation = true;
break;
case 3:
if ((OlderFolderName[2] == NewerFolderName[2]))
ifNeedOperation = true;
break;
case 4:
if ((OlderFolderName[2] == NewerFolderName[2])
&& (OlderFolderName[3] == NewerFolderName[3]))
ifNeedOperation = true;
break;
default:
break;
}
if (ifNeedOperation)
{
string[] olderVersion = OlderFolderName[1].Substring(OlderFolderName[1].IndexOf("=") + 1).Split('.');
string[] newerVersion = NewerFolderName[1].Substring(NewerFolderName[1].IndexOf("=") + 1).Split('.');
for (int x = 0; x < olderVersion.Length; x++)
{
if (Int32.Parse(olderVersion[x]) < Int32.Parse(newerVersion[x]))
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(dirs[i]);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dirs[i + 1]);
olderFolder.Add(dirs[i]);
count += 1;
i += 1;
break;
}
else if (Int32.Parse(olderVersion[x]) > Int32.Parse(newerVersion[x]))
{
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine(dirs[i]);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(dirs[i + 1]);
olderFolder.Add(dirs[i + 1]);
count += 1;
i += 1;
break;
}
}
}
}
}
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("总共有 {0} 个旧文件夹,是否删除? y--删除 n--不删除", count);
string yesDel = Console.ReadLine().Trim().ToUpper();
if (yesDel == "Y")
{
for (int i = 0; i < olderFolder.Count; i++)
{
Directory.Delete(olderFolder[i], true);
}
}
}
catch (UnauthorizedAccessException UAEx)
{
Console.WriteLine(UAEx.Message);
}
catch (PathTooLongException PathEx)
{
Console.WriteLine(PathEx.Message);
}
Console.WriteLine("执行完毕,按任意键退出。");
Console.ReadKey();
}
}
}
生成的可以执行文件放置在离线安装包文件目录(例如上面命令行所示的F:\Dev\VisualStudio\VS2017Ent)下面,执行程序可看到如下效果:
编译好的可执行文件: 点击下载