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 }
  • 相关阅读:
    Matlab矩阵填充--Matlab interp2
    Object::connect: No such slot (QT槽丢失问题)
    QT显示框架嵌入Vs控制台工程
    SLAM: 关于Orb_SLAM的使用小综述
    SLAM: Orb_SLAM中的ORB特征
    Ubuntu安装中文语言包
    装X数学:高雅的数学表示
    图像描述:各种维度图像的逻辑描述形式
    Python__configparser模块
    Python__xml模块
  • 原文地址:https://www.cnblogs.com/Clin/p/2664367.html
Copyright © 2011-2022 走看看