ini文件加编码的代码|C# 读ini文件读出来的是乱码 怎么解决

1. 求VB读写INI配置文件的方法代码。。。

建一个模块,起名为mINI,保存为“INI文件读写模块.bas”,复制以下代码:Private Declare Function GetPrivateProfileString Lib "kernel32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As String, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As LongPrivate Declare Function WritePrivateProfileString Lib "kernel32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As LongPrivate sPathFile As StringPublic Property Get PathFile() As String Dim sPath As String If sPathFile = vbNullString Then sPath = App.Path If Right(sPath, 1) = "\" Then sPath = sPath & "\" End If PathFile = sPath & App.EXEName & ".ini" Else PathFile = sPathFile End IfEnd PropertyPublic Property Let PathFile(sNewPathFile As String) sPathFile = sNewPathFileEnd PropertyPublic Function GetValue(ByVal sKey As String, Optional ByVal sDefault As String) As String GetValue = GetValueEx("参数设置", sKey, sDefault)End FunctionPublic Function GetValueEx(ByVal sMole As String, ByVal sKey As String, Optional ByVal sDefault As String) As String GetValueEx = GetValueFromFile(PathFile, sMole, sKey, sDefault)End FunctionPublic Function GetValueFromFile(ByVal sFile As String, ByVal sMole As String, ByVal sKey As String, Optional ByVal sDefault As String) As String Dim sRtn As String 'If (Not Dir(sFile) = vbNullString) And (Not Trim(sFile) = vbNullString) Then sRtn = Space(255) GetPrivateProfileString sMole, sKey, sDefault, sRtn, 255, sFile GetValueFromFile = BTrim(sRtn) 'End IfEnd FunctionPublic Function SetValue(ByVal sKey As String, ByVal sValue As String) As Boolean SetValue = SetValueEx("参数设置", sKey, sValue)End FunctionPublic Function SetValueEx(ByVal sMole As String, ByVal sKey As String, ByVal sValue As String) As Boolean SetValueEx = SetValueToFile(PathFile, sMole, sKey, sValue)End FunctionPublic Function SetValueToFile(ByVal sFile As String, ByVal sMole As String, ByVal sKey As String, ByVal sValue As String) As Boolean SetValueToFile = WritePrivateProfileString(sMole, sKey, sValue, sFile)End FunctionPrivate Function BTrim(sStr As String) As String Dim sRtn As String Dim i As Long Dim sChar As String sRtn = sStr For i = 1 To Len(sStr) sChar = Mid$(sStr, i, 1) If sChar = Chr$(0) Then sRtn = Left$(sStr, i – 1) Exit For End If Next i sRtn = Trim(sRtn) BTrim = sRtnEnd Function'里面的函数能看懂吧?用法和GetSetting、SetSetting基本一样,区别是需要指定一下ini文件的绝对路径文件件名。这段程序我用了10多年了,您可放心使用。若有问题可来信 [email protected]

2. C# 读取ini文件

using System.Runtime.InteropServices; [DllImport("kernel32.dll")] private static extern long WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32.dll")] private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath); /// <summary> /// 写入INI文件 /// </summary> /// <param name=^Section^>节点名称</param> /// <param name=^Key^>关键字</param> /// <param name=^Value^>值</param> /// <param name=^filepath^>INI文件路径</param> static public void IniWriteValue(string Section, string Key, string Value, string filepath) { WritePrivateProfileString(Section, Key, Value, filepath); } /// <summary> /// 读取INI文件 /// </summary> /// <param name=^Section^>节点名称</param> /// <param name=^Key^>关键字</param> /// <param name=^filepath^>INI文件路径</param> /// <returns>值</returns> static public string IniReadValue(string Section, string Key, string filepath) { StringBuilder temp = new StringBuilder(255); int i = GetPrivateProfileString(Section, Key, "", temp,255, filepath); return temp.ToString(); } ini 文档格式路径假设为 D:/SETUP.ini [SQL] SVRName=192.168.1.11\SQL2005 读取实例 IniReadValue("SQL", "SVRName"," D:/SETUP.ini"); 这样读取出来的值是192.168.1.11\SQL2005 写的话类似 IniReadValue("SQL", "SVRName","你要写入的值"," D:/SETUP.ini"); 补充: using System; using System.IO; using System.Runtime.InteropServices; using System.Text; using System.Collections; using System.Collections.Specialized; namespace wuyisky{ /**//**/ /**//// /// IniFiles的类 /// public class IniFiles { public string FileName; //INI文件名 //声明读写INI文件的API函数 [DllImport("kernel32")] private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath); [DllImport("kernel32")] private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath); //类的构造函数,传递INI文件名 public IniFiles(string AFileName) { // 判断文件是否存在 FileInfo fileInfo = new FileInfo(AFileName); //Todo:搞清枚举的用法 if ((!fileInfo.Exists)) { //|| (FileAttributes.Directory in fileInfo.Attributes)) //文件不存在,建立文件 System.IO.StreamWriter sw = new System.IO.StreamWriter(AFileName, false, System.Text.Encoding.Default); try { sw.Write("#表格配置档案"); sw.Close(); } catch { throw (new ApplicationException("Ini文件不存在")); } } //必须是完全路径,不能是相对路径 FileName = fileInfo.FullName; } //写INI文件 public void WriteString(string Section, string Ident, string Value) { if (!WritePrivateProfileString(Section, Ident, Value, FileName)) { throw (new ApplicationException("写Ini文件出错")); } } //读取INI文件指定 public string ReadString(string Section, string Ident, string Default) { Byte[] Buffer = new Byte[65535]; int bufLen = GetPrivateProfileString(Section, Ident, Default, Buffer, Buffer.GetUpperBound(0), FileName); //必须设定0(系统默认的代码页)的编码方式,否则无法支持中文 string s = Encoding.GetEncoding(0).GetString(Buffer); s = s.Substring(0, bufLen); return s.Trim(); } //读整数 public int ReadInteger(string Section, string Ident, int Default) { string intStr = ReadString(Section, Ident, Convert.ToString(Default)); try { return Convert.ToInt32(intStr); } catch (Exception ex) { Console.WriteLine(ex.Message); return Default; } } //写整数 public void WriteInteger(string Section, string Ident, int Value) { WriteString(Section, Ident, Value.ToString()); } //读布尔 public bool ReadBool(string Section, string Ident, bool Default) { try { return Convert.ToBoolean(ReadString(Section, Ident, Convert.ToString(Default))); } catch (Exception ex) { Console.WriteLine(ex.Message); return Default; } } //写Bool public void WriteBool(string Section, string Ident, bool Value) { WriteString(Section, Ident, Convert.ToString(Value)); } //从Ini文件中,将指定的Section名称中的所有Ident添加到列表中 public void ReadSection(string Section, StringCollection Idents) { Byte[] Buffer = new Byte[16384]; //Idents.Clear(); int bufLen = GetPrivateProfileString(Section, null, null, Buffer, Buffer.GetUpperBound(0), FileName); //对Section进行解析 GetStringsFromBuffer(Buffer, bufLen, Idents); } private void GetStringsFromBuffer(Byte[] Buffer, int bufLen, StringCollection Strings) { Strings.Clear(); if (bufLen != 0) { int start = 0; for (int i = 0; i bufLen; i++) { if ((Buffer[i] == 0) && ((i – start) > 0)) { String s = Encoding.GetEncoding(0).GetString(Buffer, start, i – start); Strings.Add(s); start = i + 1; } } } } //从Ini文件中,读取所有的Sections的名称 public void ReadSections(StringCollection SectionList) { //Note:必须得用Bytes来实现,StringBuilder只能取到第一个Section byte[] Buffer = new byte[65535]; int bufLen = 0; bufLen = GetPrivateProfileString(null, null, null, Buffer, Buffer.GetUpperBound(0), FileName); GetStringsFromBuffer(Buffer, bufLen, SectionList); } //读取指定的Section的所有Value到列表中 public void ReadSectionValues(string Section, NameValueCollection Values) { StringCollection KeyList = new StringCollection(); ReadSection(Section, KeyList); Values.Clear(); foreach (string key in KeyList) { Values.Add(key, ReadString(Section, key, "")); } } /**/////读取指定的Section的所有Value到列表中, //public void ReadSectionValues(string Section, NameValueCollection Values,char splitString) //{ string sectionValue; // string[] sectionValueSplit; // StringCollection KeyList = new StringCollection(); // ReadSection(Section, KeyList); // Values.Clear(); // foreach (string key in KeyList) // { // sectionValue=ReadString(Section, key, ""); // sectionValueSplit=sectionValue.Split(splitString); // Values.Add(key, sectionValueSplit[0].ToString(),sectionValueSplit[1].ToString()); // } //} //清除某个Section public void EraseSection(string Section) { // if (!WritePrivateProfileString(Section, null, null, FileName)) { throw (new ApplicationException("无法清除Ini文件中的Section")); } } //删除某个Section下的键 public void DeleteKey(string Section, string Ident) { WritePrivateProfileString(Section, Ident, null, FileName); } //Note:对于Win9X,来说需要实现UpdateFile方法将缓冲中的数据写入文件 //在Win NT, 2000和XP上,都是直接写文件,没有缓冲,所以,无须实现UpdateFile //执行完对Ini文件的修改之后,应该调用本方法更新缓冲区。 public void UpdateFile() { WritePrivateProfileString(null, null, null, FileName); } //检查某个Section下的某个键值是否存在 public bool ValueExists(string Section, string Ident) { // StringCollection Idents = new StringCollection(); ReadSection(Section, Idents); return Idents.IndexOf(Ident) > -1; } //确保资源的释放 ~IniFiles() { UpdateFile(); } } }

3. C# 读ini文件读出来的是乱码 怎么解决

<globalization requestEncoding="GB2312" responseEncoding="GB2312" fileEncoding="GB2312" />你看一下有没有类似于以上设置,出现乱码是因为你读取文件的编码设置和你读取文件编专码设置不属一样例如,上边是我在。net中设置的,他读取文件采用gb2312,如果你的文件使用utf-8的话,读出来就是乱码

4. c# winform 创建ini文件 看详细介绍

FileStream filest = new FileStream(@"c:\abc.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite); //指定操作系统应打开文件(如果文件存在);否则,应创建新文件。如果你INI文件需要有初始内容,那么单独判断该文件是否存在,如果不存在,就单独初始创建一个模板格式的INI。StreamReader sr = new StreamReader(filest,Encoding.GetEncoding("gb2312"));gb2312 是编码格式。支持文本中的简体中文。

5. 批处理修改ini文件的内容

不清楚你的实际文件/情况,仅以问题中的样例说明及猜测为据;以下代码复制粘贴到记事本,另存为xx.bat,编码选ANSI,跟要处理的文件放一起双击运行@echooff&cd/d"%~dp0"rem修改一个ini文件里的指定行内容set#=Anyquestions&set_=WX&set$=Q&set/az=0x53b7e0b4title%#%+%$%%$%/%_%%z%set"inifile=a.ini"ifnotexist"%inifile%"(echo;"%inifile%"patherrorornotexists&pause&exit)setuser=&set/puser=entertheuser:setlinenum=&for/f"delims=:"%%ain('type"%inifile%"^|findstr/nb/c:"user="')doset"linenum=%%a"ifdefinedlinenum(for/f"tokens=1*delims=:"%%ain('type"%inifile%"^|findstr/n.*')do(if"%%a"equ"%linenum%"(echo;user=%user%)elseecho;%%b))echo;%#%+%$%%$%/%_%%z%pauseexit

6. 求红警2尤里的复仇(RA2MD)rulesmd.ini中的代码

刚刚研究了一阵,终于明白了! 很简单!第一步:新建一个本文文档第二步:打开它,将以下代码复制进去:; Multiplayer Game Mode Rules.INI override; Mode == Team Game; This file must exist to satisfy the Multiplayer Game Mode system; Team Game is where players should join teams before starting a game, because of the map types.; there are no real changes in this mode. [MultiplayerDialogSettings]AlliesAllowed=yesAllyChangeAllowed=noMustAlly=no写好后,保存。然后最重要的,将这个文件名字改为mpteammd.ini名字一定要正确,最重要是后缀名“ini”。建议在我的电脑——(在上方)工具——文件夹选项——查看中找到 “隐藏文件类型扩展名 ”,把前面的对号去掉,确定。在“小队联盟”中就可以选择随机小队,也就是“—”了。


赞 (0)