c# 读写.ini文件
1
using System;2
2using System.Text;3
3using System.IO;4
4using System.Runtime.InteropServices;5
56
6namespace MyRWIniFile7

7
{8
8 public class OperateIniFile9

9
{10

10 API函数声明API函数声明#region API函数声明11
11 [DllImport("kernel32")]//返回0表示失败,非0为成功12
12 private static extern long WritePrivateProfileString(string section,string key,13
13 string val,string filePath);14
1415
15 [DllImport("kernel32")]//返回取得字符串缓冲区的长度16
16 private static extern long GetPrivateProfileString(string section,string key,17
17 string def,StringBuilder retVal,int size,string filePath);18
18 #endregion19
1920

20 读Ini文件读Ini文件#region 读Ini文件21
21 public static string ReadIniData(string Section,string Key,string NoText,string iniFilePath)22

22
{23
23 if(File.Exists(iniFilePath))24

24
{25
25 StringBuilder temp = new StringBuilder(1024);26
26 GetPrivateProfileString(Section,Key,NoText,temp,1024,iniFilePath);27
27 return temp.ToString();28
28 }29
29 else30

30
{31
31 return String.Empty;32
32 }33
33 }34
34 #endregion35
3536

36 写Ini文件写Ini文件#region 写Ini文件37
37 public static bool WriteIniData(string Section,string Key,string Value,string iniFilePath)38

38
{39
39 if(File.Exists(iniFilePath))40

40
{41
41 long OpStation = WritePrivateProfileString(Section,Key,Value,iniFilePath); 42
42 if(OpStation == 0)43

43
{44
44 return false;45
45 }46
46 else47

47
{48
48 return true;49
49 }50
50 }51
51 else52

52
{53
53 return false;54
54 }55
55 }56
56 #endregion57
57 }58
58}59
