JS通过ActiveX读写ini配置文件
1 String.prototype.trim = function(){ 2 return this.replace(/(^\s+)|(\s+$)/g, ''); 3 }; 4 5 IniConfig = function(iniFileName) { 6 this.iniFileName = iniFileName; 7 this._iniSecDictionary = new Array(); 8 this.fso = new ActiveXObject("Scripting.FileSystemObject"); 9 } 10 11 IniConfig.prototype._checkFile = function(){ 12 if (!this.fso.FileExists(this.iniFileName)){ 13 this.fso.CreateTextFile(this.iniFileName, true, true); 14 } 15 } 16 17 IniConfig.prototype.load = function(){ 18 this._checkFile(); 19 var currSecName = null; 20 var fs = this.fso.OpenTextFile(this.iniFileName, 1, false, -1); 21 22 while (!fs.AtEndOfStream) { 23 var strLine = fs.ReadLine().trim(); 24 if (strLine.length > 0){ 25 var firchCh = strLine.substr(0, 1); 26 if (firchCh != ';'){ 27 if (firchCh == '['){ 28 var secName = strLine.substr(1, strLine.length - 2); 29 currSecName = secName; 30 this._iniSecDictionary[secName] = new Array(); 31 } else { 32 var idx = strLine.indexOf('='); 33 var strKey = strLine.substring(0, idx); 34 var strVal = strLine.substr(idx + 1); 35 if (currSecName == null){ 36 throw ("Ini文件格式不正确!"); 37 } 38 this._iniSecDictionary[currSecName][strKey] = strVal; 39 } 40 } 41 } 42 } 43 fs.Close(); 44 fs = null; 45 } 46 47 IniConfig.prototype.save = function(){ 48 this._checkFile(); 49 var dic = this._iniSecDictionary; 50 var currSecName = null; 51 var fs = this.fso.OpenTextFile(this.iniFileName, 2, true, -1); 52 for (var sec in dic){ 53 fs.WriteLine('[' + sec + ']'); 54 for (var key in dic[sec]){ 55 fs.WriteLine(key + '=' + dic[sec][key]); 56 } 57 } 58 fs.Close(); 59 fs = null; 60 } 61 62 IniConfig.prototype.get = function(secName, keyName) { 63 var dic = this._iniSecDictionary; 64 try{ 65 return dic[secName][keyName]; 66 } catch (e) { 67 return ''; 68 } 69 } 70 71 IniConfig.prototype.set = function(secName, keyName, val) { 72 var dic = this._iniSecDictionary; 73 try { 74 if (dic[secName] == null) { 75 dic[secName] = new Array(); 76 } 77 dic[secName][keyName] = val; 78 } catch (e) { 79 alert(e.message); 80 } 81 } 82 83 try { 84 var iniFile = new IniConfig("E:\\a.ini"); 85 iniFile.load(); 86 alert(iniFile.get("Shutdown","0CmdLine")); 87 iniFile.set("Shutdown","0CmdLine","aaa"); 88 iniFile.set("Shutdown","0CmdLine","abc"); 89 iniFile.set("Shutdown", "1CmdLine", "bbb") 90 iniFile.save(); 91 } catch(e) { 92 alert(e.message); 93 }