usingSystem;usingSystem.Text;usingSystem.IO;usingSystem.Runtime.InteropServices;usingSystem.Collections.Generic; Public classOperateinifile {Private StaticString FilePath ="";#regionAPI function Declaration[DllImport ("kernel32")]Private Static extern LongWritePrivateProfileString (stringSectionstringKey,stringValstringFilePath);
//overload that requires calling GetPrivateProfileString [DllImport ("kernel32", EntryPoint ="getprivateprofilestring")] Private Static extern LongGetPrivateProfileString (stringSectionstringKey,stringDef, StringBuilder RetVal,intSizestringFilePath); [DllImport ("kernel32", EntryPoint ="getprivateprofilestring")] Private Static extern UINTGetprivateprofilestringa (stringSectionstringKey,stringDef, byte[] RetVal,intSizestringFilePath); #endregion Public Staticlist<string>readsections () {returnreadsections (FilePath); } Public Staticlist<string> Readsections (stringinifilename) {List<string> result =Newlist<string>(); Byte[] BUF=Newbyte[65536]; UINTLen = Getprivateprofilestringa (NULL,NULL,NULL, buf, buf. Length, Inifilename); intj =0; for(inti =0; i < Len; i++) if(Buf[i] = =0) {result. ADD (Encoding.Default.GetString (buf, J, I-j)); J= i +1; } returnresult; } Public Staticlist<string>Readkeys (String sectionname) {returnReadkeys (sectionname, FilePath); } Public Staticlist<string> Readkeys (stringSectionName,stringinifilename) {List<string> result =Newlist<string>(); Byte[] BUF=Newbyte[65536]; UINTLen = Getprivateprofilestringa (sectionname,NULL,NULL, buf, buf. Length, Inifilename); intj =0; for(inti =0; i < Len; i++) if(Buf[i] = =0) {result. ADD (Encoding.Default.GetString (buf, J, I-j)); J= i +1; } returnresult; } Public Static voidSetFilePath (String filepath) {filepath=filepath; } #regionRead INI file Public Static stringReadinidata (stringSection,stringKey,stringNotext) { returnreadinidata (section, Key, Notext, FilePath); }
Public Static stringReadinidata (stringSection,stringKey,stringNotext,stringIniFilePath) { if(File.exists (IniFilePath)) {StringBuilder temp=NewStringBuilder (1024x768); GetPrivateProfileString (section, Key, Notext, temp,1024x768, IniFilePath); returntemp. ToString (); } ElsereturnString.Empty; } #endregion #regionWrite INI file Public Static BOOLWriteinidata (stringSection,stringKey,stringValue) { returnwriteinidata (section, Key, Value, FilePath); } Public Static BOOLWriteinidata (stringSection,stringKey,stringValue,stringIniFilePath) { if(File.exists (IniFilePath)) {LongOpstation =writeprivateprofilestring (section, Key, Value, IniFilePath); if(Opstation = =0) return false; Elsereturn true; } Elsereturn false; } #endregion }
C # gets all the sections in the INI file to get all the keys under the section