使用C#来清除系统环境变量中无效的路径

主要使用到Envrionment类的设置和获取环境变量的方法,见具体的代码吧。

//	File Name:	CleanEnvironmentVariables.cs
//	Author:			Peng QianHe
//	Date:				2012.9.13

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace QhCSharp{
	class CleanEnvironmentVariables{
		private static Dictionary<string,string> needProcess = new Dictionary<string,string>();
				
		private static bool IsPath(string path){
			char[] invalidPathChars = Path.GetInvalidPathChars();
			foreach(char invalidPathChar in invalidPathChars){
				if(path.Contains(invalidPathChar.ToString())){
					return false;
				}
			}
			
			if( !path.Contains(":") ){
				return false;
			}
			
			return true;
		}
		
		private static void CleanSpecifiedVariables(EnvironmentVariableTarget target){
			try{			
				// Analysis each environment variables and delete the non-exist path
				foreach(DictionaryEntry de in Environment.GetEnvironmentVariables(target)){
					Console.Write("Analysising [{0}]{1} ......",target,de.Key);
					
					string[] dirs = de.Value.ToString().Split(';');
					string newValue = string.Empty;
					foreach(string dir in dirs){
						if(dir != string.Empty){
							if( IsPath(dir) ){
								DirectoryInfo d = new DirectoryInfo(dir);
								string fileName = Path.GetFileName(dir);
								if(!d.Exists){
									if(fileName == string.Empty){
										// Console.WriteLine("Path: {0} is not exist.",dir);
									}else{
										FileInfo f = new FileInfo(dir);
										if(!f.Exists){
											// Console.WriteLine("Path: {0} is not exist.",dir);
										}else{
											newValue += dir + (dirs.Length>1?";":"");
										}
									}
								}else{
									newValue += dir+ (dirs.Length>1?";":"");
								}
							}else{
								// Console.WriteLine("{0} is not a valid path.",dir);
								newValue += dir+ (dirs.Length>1?";":"");
							}
						}
					}
					
					Console.SetCursorPosition(60,Console.CursorTop);
					
					// Console.WriteLine("{0} = {1}",de.Key,newValue);
					if(newValue != string.Empty){
						if(newValue == de.Value.ToString() || de.Value.ToString() == newValue.Substring(0,newValue.Length-1)){
							Console.Write(" [No Need]\r\n");
						}else{
							Console.WriteLine(" [Be Changed]",de.Key);
							// Console.WriteLine("{0} = {1}",de.Key,newValue);
							
							needProcess.Add(de.Key.ToString(),newValue);
						}
					}else{
						Console.WriteLine(" [Can Deleted]",de.Key);
						needProcess.Add(de.Key.ToString(),newValue);
					}
				}
				
				// User decided to process or not
				if(needProcess.Count > 1){
					Console.Write("Do you want to process or not?(y/n) ");
					ConsoleKeyInfo pressedKey = Console.ReadKey();
					Console.WriteLine();
					if(pressedKey.KeyChar == 'y' || pressedKey.KeyChar == 'Y'){
						foreach(KeyValuePair<string,string> d in needProcess){
							Environment.SetEnvironmentVariable(d.Key,d.Value,target);
							Console.WriteLine("{0} = {1}",d.Key,d.Value);
						}
					}
				}else{
					Console.WriteLine("No need to process any environment variables.");
				}
			}catch(Exception e){
				Console.WriteLine(e.Message);
			}
		}
		
		public static void Main(string[] args){
			Console.Write("Which Environment Variables to clean?(1->User,2->Machine,3->Process) ");
			ConsoleKeyInfo key = Console.ReadKey();
			Console.WriteLine();
			switch(key.KeyChar){
				case '1':
					CleanSpecifiedVariables(EnvironmentVariableTarget.User);
					break;
					
				default:
				case '2':
					CleanSpecifiedVariables(EnvironmentVariableTarget.Machine);
					break;
					
				case '3':
					CleanSpecifiedVariables(EnvironmentVariableTarget.Process);
					break;
			}
		}		
	}
}

效果图:

使用C#来清除系统环境变量中无效的路径_第1张图片

但是,有一个问题是,设置Process中的环境变量的时候,没有效果。不清楚是为什么了。

【更多阅读】

  1. [原]Baidu:C#利用百度来搜索网页、图片、视频等等
  2. [原]WMICodeCreator:C#产生WMI代码的工具
  3. [原]ManageStartUpApps:C#操作注册表来读取和修改开机启动项
  4. [原]GetAlpha:C#实现获取网页验证码图片,并识别出其中的字母
  5. [原]GetIcons:C#提取应用程序的图标资源
  6. [原]Cls_Ini.cls:VB写的操作ini配置文件的类
  7. [译]用C#检测你的打印机是否连接
  8. [原]Hotkey.cs:为应用程序添加热键
  9. [原]PjConvertImageFormat:用FreeImage.NET写的一个35种图像格式转换程序
  10. [译]用C#检测你的打印机是否连接

你可能感兴趣的:(使用C#来清除系统环境变量中无效的路径)