基于C#winform设计。

首先创建一个类,我命名为IniFiles。并引入命名空间using System.Runtime.InteropServices;

接着,声明API函数

      [DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

写入INI函数方法

   /// <summary>
/// 写入INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
/// <param name="Value">值</param>
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.inipath);
}

读取INI文件方法

 /// <summary>
/// 读出INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(500);
int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
return temp.ToString();
}

验证文件是否存在

         /// <summary>
/// 验证文件是否存在
/// </summary>
/// <returns>布尔值</returns>
public bool ExistINIFile()
{
return File.Exists(inipath);
}

在其他窗体页面如何条用?请看:

这时候是创建INI文件(位置一般处于资源文件下bin\Debug目录)

public partial class Frm_Login : Form
{
HotelSystemORM.Unitl.IniFiles ini = new HotelSystemORM.Unitl.IniFiles(Application.StartupPath + @"\MyConfig.INI");//Application.StartupPath只适用于winform窗体程序
}

生成了文件之后就可以写入和读取信息了。

ini.IniWriteValue("登入详细", "账号", "test");
ini.IniWriteValue("登入详细", "密码", "password");

读取登入信息(页面加载的时候)

if (ini.ExistINIFile())//验证是否存在文件,存在就读取
label1.Text = ini.IniReadValue("登入详细", "用户名");

完成!

IniFiles类全部完整代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.InteropServices; namespace WindowsFormsApplication1
{
public class IniFiles
{
public string inipath; //声明API函数 [DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
/// <summary>
/// 构造方法
/// </summary>
/// <param name="INIPath">文件路径</param>
public IniFiles(string INIPath)
{
inipath = INIPath;
} public IniFiles() { } /// <summary>
/// 写入INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
/// <param name="Value">值</param>
public void IniWriteValue(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.inipath);
}
/// <summary>
/// 读出INI文件
/// </summary>
/// <param name="Section">项目名称(如 [TypeName] )</param>
/// <param name="Key">键</param>
public string IniReadValue(string Section, string Key)
{
StringBuilder temp = new StringBuilder(500);
int i = GetPrivateProfileString(Section, Key, "", temp, 500, this.inipath);
return temp.ToString();
}
/// <summary>
/// 验证文件是否存在
/// </summary>
/// <returns>布尔值</returns>
public bool ExistINIFile()
{
return File.Exists(inipath);
}
}
}

页面调用:

     public class INIOperationClass
{ #region INI文件操作 /*
* 针对INI文件的API操作方法,其中的节点(Section)、键(KEY)都不区分大小写
* 如果指定的INI文件不存在,会自动创建该文件。
*
* CharSet定义的时候使用了什么类型,在使用相关方法时必须要使用相应的类型
* 例如 GetPrivateProfileSectionNames声明为CharSet.Auto,那么就应该使用 Marshal.PtrToStringAuto来读取相关内容
* 如果使用的是CharSet.Ansi,就应该使用Marshal.PtrToStringAnsi来读取内容
*
*/ #region API声明 /// <summary>
/// 获取所有节点名称(Section)
/// </summary>
/// <param name="lpszReturnBuffer">存放节点名称的内存地址,每个节点之间用\0分隔</param>
/// <param name="nSize">内存大小(characters)</param>
/// <param name="lpFileName">Ini文件</param>
/// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, uint nSize, string lpFileName); /// <summary>
/// 获取某个指定节点(Section)中所有KEY和Value
/// </summary>
/// <param name="lpAppName">节点名称</param>
/// <param name="lpReturnedString">返回值的内存地址,每个之间用\0分隔</param>
/// <param name="nSize">内存大小(characters)</param>
/// <param name="lpFileName">Ini文件</param>
/// <returns>内容的实际长度,为0表示没有内容,为nSize-2表示内存大小不够</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileSection(string lpAppName, IntPtr lpReturnedString, uint nSize, string lpFileName); /// <summary>
/// 读取INI文件中指定的Key的值
/// </summary>
/// <param name="lpAppName">节点名称。如果为null,则读取INI中所有节点名称,每个节点名称之间用\0分隔</param>
/// <param name="lpKeyName">Key名称。如果为null,则读取INI中指定节点中的所有KEY,每个KEY之间用\0分隔</param>
/// <param name="lpDefault">读取失败时的默认值</param>
/// <param name="lpReturnedString">读取的内容缓冲区,读取之后,多余的地方使用\0填充</param>
/// <param name="nSize">内容缓冲区的长度</param>
/// <param name="lpFileName">INI文件名</param>
/// <returns>实际读取到的长度</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, [In, Out] char[] lpReturnedString, uint nSize, string lpFileName); //另一种声明方式,使用 StringBuilder 作为缓冲区类型的缺点是不能接受\0字符,会将\0及其后的字符截断,
//所以对于lpAppName或lpKeyName为null的情况就不适用
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, StringBuilder lpReturnedString, uint nSize, string lpFileName); //再一种声明,使用string作为缓冲区的类型同char[]
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
private static extern uint GetPrivateProfileString(string lpAppName, string lpKeyName, string lpDefault, string lpReturnedString, uint nSize, string lpFileName); /// <summary>
/// 将指定的键值对写到指定的节点,如果已经存在则替换。
/// </summary>
/// <param name="lpAppName">节点,如果不存在此节点,则创建此节点</param>
/// <param name="lpString">Item键值对,多个用\0分隔,形如key1=value1\0key2=value2
/// <para>如果为string.Empty,则删除指定节点下的所有内容,保留节点</para>
/// <para>如果为null,则删除指定节点下的所有内容,并且删除该节点</para>
/// </param>
/// <param name="lpFileName">INI文件</param>
/// <returns>是否成功写入</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.Bool)] //可以没有此行
private static extern bool WritePrivateProfileSection(string lpAppName, string lpString, string lpFileName); /// <summary>
/// 将指定的键和值写到指定的节点,如果已经存在则替换
/// </summary>
/// <param name="lpAppName">节点名称</param>
/// <param name="lpKeyName">键名称。如果为null,则删除指定的节点及其所有的项目</param>
/// <param name="lpString">值内容。如果为null,则删除指定节点中指定的键。</param>
/// <param name="lpFileName">INI文件</param>
/// <returns>操作是否成功</returns>
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool WritePrivateProfileString(string lpAppName, string lpKeyName, string lpString, string lpFileName); #endregion #region 封装 /// <summary>
/// 读取INI文件中指定INI文件中的所有节点名称(Section)
/// </summary>
/// <param name="iniFile">Ini文件</param>
/// <returns>所有节点,没有内容返回string[0]</returns>
public static string[] INIGetAllSectionNames(string iniFile)
{
uint MAX_BUFFER = ; //默认为32767 string[] sections = new string[]; //返回值 //申请内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char));
uint bytesReturned = INIOperationClass.GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFile);
if (bytesReturned != )
{
//读取指定内存的内容
string local = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned).ToString(); //每个节点之间用\0分隔,末尾有一个\0
sections = local.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
} //释放内存
Marshal.FreeCoTaskMem(pReturnedString); return sections;
} /// <summary>
/// 获取INI文件中指定节点(Section)中的所有条目(key=value形式)
/// </summary>
/// <param name="iniFile">Ini文件</param>
/// <param name="section">节点名称</param>
/// <returns>指定节点中的所有项目,没有内容返回string[0]</returns>
public static string[] INIGetAllItems(string iniFile, string section)
{
//返回值形式为 key=value,例如 Color=Red
uint MAX_BUFFER = ; //默认为32767 string[] items = new string[]; //返回值 //分配内存
IntPtr pReturnedString = Marshal.AllocCoTaskMem((int)MAX_BUFFER * sizeof(char)); uint bytesReturned = INIOperationClass.GetPrivateProfileSection(section, pReturnedString, MAX_BUFFER, iniFile); if (!(bytesReturned == MAX_BUFFER - ) || (bytesReturned == ))
{ string returnedString = Marshal.PtrToStringAuto(pReturnedString, (int)bytesReturned);
items = returnedString.Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
} Marshal.FreeCoTaskMem(pReturnedString); //释放内存 return items;
} /// <summary>
/// 获取INI文件中指定节点(Section)中的所有条目的Key列表
/// </summary>
/// <param name="iniFile">Ini文件</param>
/// <param name="section">节点名称</param>
/// <returns>如果没有内容,反回string[0]</returns>
public static string[] INIGetAllItemKeys(string iniFile, string section)
{
string[] value = new string[];
const int SIZE = * ; if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} char[] chars = new char[SIZE];
uint bytesReturned = INIOperationClass.GetPrivateProfileString(section, null, null, chars, SIZE, iniFile); if (bytesReturned != )
{
value = new string(chars).Split(new char[] { '\0' }, StringSplitOptions.RemoveEmptyEntries);
}
chars = null; return value;
} /// <summary>
/// 读取INI文件中指定KEY的字符串型值
/// </summary>
/// <param name="iniFile">Ini文件</param>
/// <param name="section">节点名称</param>
/// <param name="key">键名称</param>
/// <param name="defaultValue">如果没此KEY所使用的默认值</param>
/// <returns>读取到的值</returns>
public static string INIGetStringValue(string iniFile, string section, string key, string defaultValue)
{
string value = defaultValue;
const int SIZE = * ; if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称(key)", "key");
} StringBuilder sb = new StringBuilder(SIZE);
uint bytesReturned = INIOperationClass.GetPrivateProfileString(section, key, defaultValue, sb, SIZE, iniFile); if (bytesReturned != )
{
value = sb.ToString();
}
sb = null; return value;
} /// <summary>
/// 在INI文件中,将指定的键值对写到指定的节点,如果已经存在则替换
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点,如果不存在此节点,则创建此节点</param>
/// <param name="items">键值对,多个用\0分隔,形如key1=value1\0key2=value2</param>
/// <returns></returns>
public static bool INIWriteItems(string iniFile, string section, string items)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} if (string.IsNullOrEmpty(items))
{
throw new ArgumentException("必须指定键值对", "items");
} return INIOperationClass.WritePrivateProfileSection(section, items, iniFile);
} /// <summary>
/// 在INI文件中,指定节点写入指定的键及值。如果已经存在,则替换。如果没有则创建。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <param name="value">值</param>
/// <returns>操作是否成功</returns>
public static bool INIWriteValue(string iniFile, string section, string key, string value)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称", "key");
} if (value == null)
{
throw new ArgumentException("值不能为null", "value");
} return INIOperationClass.WritePrivateProfileString(section, key, value, iniFile); } /// <summary>
/// 在INI文件中,删除指定节点中的指定的键。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <param name="key">键</param>
/// <returns>操作是否成功</returns>
public static bool INIDeleteKey(string iniFile, string section, string key)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} if (string.IsNullOrEmpty(key))
{
throw new ArgumentException("必须指定键名称", "key");
} return INIOperationClass.WritePrivateProfileString(section, key, null, iniFile);
} /// <summary>
/// 在INI文件中,删除指定的节点。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <returns>操作是否成功</returns>
public static bool INIDeleteSection(string iniFile, string section)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} return INIOperationClass.WritePrivateProfileString(section, null, null, iniFile);
} /// <summary>
/// 在INI文件中,删除指定节点中的所有内容。
/// </summary>
/// <param name="iniFile">INI文件</param>
/// <param name="section">节点</param>
/// <returns>操作是否成功</returns>
public static bool INIEmptySection(string iniFile, string section)
{
if (string.IsNullOrEmpty(section))
{
throw new ArgumentException("必须指定节点名称", "section");
} return INIOperationClass.WritePrivateProfileSection(section, string.Empty, iniFile);
} private void TestIniINIOperation()
{ string file = "F:\\TestIni.ini"; //写入/更新键值
INIWriteValue(file, "Desktop", "Color", "Red");
INIWriteValue(file, "Desktop", "Width", ""); INIWriteValue(file, "Toolbar", "Items", "Save,Delete,Open");
INIWriteValue(file, "Toolbar", "Dock", "True"); //写入一批键值
INIWriteItems(file, "Menu", "File=文件\0View=视图\0Edit=编辑"); //获取文件中所有的节点
string[] sections = INIGetAllSectionNames(file); //获取指定节点中的所有项
string[] items = INIGetAllItems(file, "Menu"); //获取指定节点中所有的键
string[] keys = INIGetAllItemKeys(file, "Menu"); //获取指定KEY的值
string value = INIGetStringValue(file, "Desktop", "color", null); //删除指定的KEY
INIDeleteKey(file, "desktop", "color"); //删除指定的节点
INIDeleteSection(file, "desktop"); //清空指定的节点
INIEmptySection(file, "toolbar"); }
#endregion #endregion
}

C# 创建INI文件,写入并可读取。----转载的更多相关文章

  1. C#如何读写和创建INI文件(经典)转

    C#如何读写和创建INI文件 分类: c#程序设计2011-11-27 20:42 4935人阅读 评论(2) 收藏 举报 inic#stringbuffernullfile 在做项目过程中,有时需要 ...

  2. IDEA中怎么创建ini文件

    首先博主在这使用的是idea的2019.3.2的版本,不知道的话可以打开help菜单的about查看 第一步: 具体需要在setings安装ini插件 第二步: 在File Types中查看ini,没 ...

  3. C#如何读写和创建INI文件

    在做项目过程中,有时需要保存一些简单的配置信息,可以使用xml,也可以使用INI文件.下面是C#中读取INI的方法,相信大部分朋友都使用过这种方式.INI文件的存储方式如下, [section] ke ...

  4. pycharm新建ini文件或创建ini文件失败

    1.pycharm创建ini格式的文件,没有对应的 ini 文件类型-------需要更新 Ini 2.setting–>marketplace 搜索 Ini ,然后进行安装,重启pycharm ...

  5. delphi读取ini文件

    ini文件在系统配置及应用程序参数保存与设置方面,具有很重要的作用,所以可视化的编程一族,如vb.vc.vfp.delphi等都提供了读写ini文件的方法,其中delphi中操作ini文件,最为简洁, ...

  6. INI文件的读取(C语言:GetPrivateProfileString/GetPrivateProfileInt)

    INI文件格式说明 /********************************************* ini文件说明 ini文件是文本文件,由节点(Section)和键值对(key=val ...

  7. php如何读取ini文件

    很多时候,我们使用配置文件来读取配置,那么php如何使用ini文件呢? 代码如下: 例如将:数据库信息存到ini文件中,进行读取. <?php header('content-type:text ...

  8. Delphi ini文件读写

    参考:http://www.cnblogs.com/zhangzhifeng/archive/2011/12/01/2270267.html 一.ini文件的结构 ;这是关于 ini 文件的注释 [节 ...

  9. Delphi操作Ini文件

    Delphi提供了一个TInifile类,使我们可以非常灵活的处理INI文件 一.INI文件的结构[小节名]ini文件       关键字1=值1       关键子2=值2INI文件允许有多个小节, ...

随机推荐

  1. Laravel Vuejs 实战:开发知乎 (1)项目环境配置和用户表设计

    1.使用laragon新建laravel项目 zhihu 2.配置env文件的database设置 DB_DATABASE=zhihu 3.分析users表需要的字段 4.修改数据库迁移文件: cla ...

  2. [理解] C++ 中的 源文件 和 头文件

    我是学 C井 的, 现在在工作中主要使用的编程语言是 Java, 还记得当初在第一次接触到 Cpp 的时候, 听到的第一个概念就是 Cpp 的头文件和源文件, 当初理解了好久, 死活都弄不明白, 现在 ...

  3. RestTemplate的异常 Not enough variables available to expand

    当使用 RestTemplate 可能会遇到异常: Not enough variables available to expand 典型如下: @Autowired private RestTemp ...

  4. 在visual studio中快速添加代码段

    昨天我在网课上,看到老师输入#2之后,立马就出现了一堆代码. 我于是赶紧打开自己的visual studio尝试一下,并没有任何反应. 上网查找,发现visual studio有自定义代码段的功能. ...

  5. Lesson 16 The modern city

    What is the author's main argument about the modern city? In the organization of industrial life the ...

  6. PTA的Python练习题(三)

    继续在PTA上编写Python的编程题. 从 第2章-11 求平方与倒数序列的部分和 开始 1. a,b=map(int,input().split()) s=0 while(a<=b): s= ...

  7. centos将celery写入系统服务

    第一步: 在/etc/下创建目录 celery/celery.conf 代码如下: CELERYD_NODES='w1 w2 w3' # 启动的celery进程的进程名 CELERY_BIN='/ro ...

  8. LDAP-轻量级目录访问协议(统一认证)

    概念 LDAP是轻量目录访问协议,英文全称是Lightweight Directory Access Protocol,一般都简称为LDAP. 参考资料 LDAP概念和原理介绍 我花了一个五一终于搞懂 ...

  9. 使用tag标签是SEO优化的重要性是什么?

    使用tag标签是SEO优化的重要性是什么? tag标签是一种SEO技术,在网站优化的过程中,更准确.更具体地用关键词对文章进行分类,对SEO优化具有重要的作用. 但是,很多新人站长在发表文章时不太注意 ...

  10. 【转】python创建和删除文件

    #!/usr/bin/python #-*-coding:utf-8-*- #指定编码格式,python默认unicode编码 import os directory = "./dir&qu ...