C#對INI文件操作簡單分析
C#語言還是比較常見的東西,這里我們主要介紹C#對INI文件操作,包括介紹對INI文件進(jìn)行寫操作等方面。
C#對INI文件操作
對INI文件進(jìn)行寫操作,是通過組件button2的"Click"事件來實(shí)現(xiàn)的。這里有一點(diǎn)應(yīng)該注意,當(dāng)在調(diào)用 WritePrivateProfileString()對INI文件進(jìn)行寫操作的時(shí)候,如果此時(shí)在INI文件中存在和要寫入的信息相同的段落名稱和關(guān)鍵字,則將覆蓋此INI信息。下面是button2組件的"Click"事件對應(yīng)的代碼清單:
- private void button2_Click ( object sender , System.EventArgs e )
- {
- string FileName = textBox1.Text ;
- string section = textBox2.Text ;
- string key = textBox3.Text ;
- string keyValue = textBox4.Text ;
- WritePrivateProfileString ( section , key , keyValue , FileName ) ;
- MessageBox.Show( "成功寫入INI文件!" , "信息" ) ;
- }
正確讀取INI的必須滿足三個(gè)前提:INI文件的全路徑、段落名稱和關(guān)鍵字名稱。否則就無法正確讀取。你可以設(shè)定讀取不成功后的缺省數(shù)值,在下面的程序中,為了直觀設(shè)定的是“無法讀取對應(yīng)數(shù)值!”字符串,讀取INI文件是通過button3組件的“Click”事件來實(shí)現(xiàn)的,下面是其對應(yīng)的代碼清單:
- private void button3_Click ( object sender , System.EventArgs e )
- {
- StringBuilder temp = new StringBuilder ( 255 ) ;
- string FileName = textBox1.Text ;
- string section = textBox2.Text ;
- string key = textBox3.Text ;
- int i = GetPrivateProfileString ( section , key ,"無法讀取對應(yīng)數(shù)值!",
- temp , 255 , FileName ) ;
- //顯示讀取的數(shù)值
- textBox4.Text = temp.ToString( ) ;
- }
以上介紹C#對INI文件操作
【編輯推薦】