zoukankan      html  css  js  c++  java
  • C# 读写ini文件

     1 using System;
     2 using System.Text;
     3 using System.IO;
     4 using System.Runtime.InteropServices;
     5 
     6 public class IniFile{
     7     public string path;
     8 
     9     [DllImport("kernel32")]//返回0表示失败,非0为成功
    10     private static extern long WritePrivateProfileString(string section, string key, 
    11             string val, string filePath);
    12 
    13     [DllImport("kernel32")]//返回取得字符串缓冲区的长度
    14     private static extern long GetPrivateProfileString(string section, string key,
    15             string defVal, StringBuilder retVal, int size, string filePath);
    16 
    17     public IniFile(string fullPath){
    18         if (!File.Exists(fullPath)){
    19             //文件不存在,建立文件
    20             System.IO.StreamWriter sw = new System.IO.StreamWriter(fullPath, false, System.Text.Encoding.Default);
    21             try{
    22                 sw.Write("#配置文件");
    23                 sw.Close();
    24             }
    25             catch{
    26                 throw (new ApplicationException("Ini文件不存在"));
    27             }
    28         }
    29         path = fullPath;
    30     }
    31 
    32     //ini 文件读取值 注意要是没有值返回的是个空串而不是null
    33     public string Get(string section, string key){   
    34         if (File.Exists(this.path)){
    35             int readLength = 256;
    36             StringBuilder data = new StringBuilder(readLength);
    37             GetPrivateProfileString(section, key, "", data, readLength, this.path);
    38             return data.ToString();
    39         }
    40         else {
    41             return string.Empty;
    42         }
    43     }
    44 
    45     //ini 文件写值 value 为 string类型时
    46     public bool Set(string section, string key, string value){
    47         if (File.Exists(this.path))        {
    48             long opState = WritePrivateProfileString(section, key, value, this.path);
    49             if (opState != 0){
    50                 return true;
    51             }
    52         }
    53         return false;
    54     }
    55 
    56     //ini 文件写值 value 为 int类型时
    57     public bool Set(string section, string key, int value){
    58         if (File.Exists(this.path)){
    59             string strValue = string.Format("%d", value);
    60             long opState = WritePrivateProfileString(section, key, strValue, this.path);
    61             if (opState != 0){
    62                 return true;
    63             }
    64         }
    65         return false;
    66     }
    67 }
  • 相关阅读:
    创建共享内存函数CreateFileMapping()详解
    窗口类、窗口类对象与窗口
    ubuntu中文版切换为英文后字体变化问题解决
    安装ubuntu12.04LTS卡住以及花屏问题
    时钟周期、振荡周期、机器周期、CPU周期、状态周期、指令周期、总线周期、任务周期
    波特率
    myod
    mycp
    20165226 2017-2018-2《Java程序设计》课程总结
    2017-2018-2 20165226 实验五《网络编程与安全》实验报告
  • 原文地址:https://www.cnblogs.com/Clin/p/2664367.html
Copyright © 2011-2022 走看看