using System.IO;
static void Main()
        {
            string ServerName = "";//数据库服务器名称
            string DBname = "";//数据库名称
            string strLine;
            int ZeroIndex;
            AppPath = Application.StartupPath;
            FileInfo YnExist = new FileInfo(AppPath + "\\my.ini");
            string pwdstr = "";
            //读取系统设置文件,如果系统参数设置不正确,则系统无法启动
            if (YnExist.Exists)
            {                System.IO.StreamReader SetContent = YnExist.OpenText();
                strLine = SetContent.ReadLine();//行读取并读完
                while (strLine != null)
                {
                    if (((strLine.Trim()).ToUpper()).StartsWith("SERVERNAME"))
                    {
                        ZeroIndex = strLine.IndexOf("=", 0, strLine.Length);
                        if (ZeroIndex > -1) ServerName = strLine.Substring(ZeroIndex + 1, strLine.Length - ZeroIndex - 1);
                    }
                    else if (((strLine.Trim()).ToUpper()).StartsWith("DBNAME"))
                    {
                        ZeroIndex = strLine.IndexOf("=", 0, strLine.Length);
                        if (ZeroIndex > -1) DBname = strLine.Substring(ZeroIndex + 1, strLine.Length - ZeroIndex - 1);
                    }
                    else if (((strLine.Trim()).ToUpper()).StartsWith("YNDYPRE"))
                    {
                        ZeroIndex = strLine.IndexOf("=", 0, strLine.Length);
                        if (ZeroIndex > -1) yndypre = strLine.Substring(ZeroIndex + 1, strLine.Length - ZeroIndex - 1).ToUpper();
                    }
                    else if (((strLine.Trim()).ToUpper()).StartsWith("PWD"))
                    {
                        ZeroIndex = strLine.IndexOf("=", 0, strLine.Length);
                        if (ZeroIndex > -1) pwdstr = strLine.Substring(ZeroIndex + 1, strLine.Length - ZeroIndex - 1);
                    }
                    strLine = SetContent.ReadLine();
                }
                SetContent.Close();
            }
            else
            {
                MessageBox.Show("系统主目录中my文件不正确,无法启动系统!");
                return;
            }
            //将系统设置中数据库信息读入全局变量中Driver={Sybase System 11}"
            ConnStr = "Driver={Sybase System 11};uid=sa;db=" + DBname + ";srvr=" + ServerName + ";pwd=" + pwdstr + "";
            Conn.ConnectionString = ConnStr;
            
            try
            {
                Conn.Open();
            }
            catch (Exception f)
            {
                MessageBox.Show(f.Message);
                //MessageBox.Show("系统SET文件中数据库服务或库名设置不正确,无法启动系统!");
                return;
            }
            userid = "";
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Mutex mutex = new Mutex(false, "ThisShouldOnlyRunOnce");
            //判断互斥体是否使用中。即同一程序不循序启动多个
            bool Running = !mutex.WaitOne(0, false);
            //判断程序是否启动
            if (!Running)
                Application.Run(new login());
            else
                MessageBox.Show("应用程序已经启动!");            if (userid.Trim() != "") Application.Run(new mainfm());
        }

解决方案 »

  1.   

    把下面的代码改动一下,就可以在你的程序中使用,当然 
    别忘记加上名字空间哦。 
    using System; 
    using System.IO; 
    using System.Runtime.InteropServices; 
    using System.Text; 
    namespace Sx_Mdi 
    { /// <summary> 
    /// Summary description for Class1. 
    /// </summary> 
    public class IniFile 

    //文件INI名称 
    public string Path; ////声明读写INI文件的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文件名 
    public IniFile(string inipath) 

    // 
    // TODO: Add constructor logic here 
    // 
    Path = inipath; 
    } //写INI文件 
    public void IniWriteValue(string Section,string Key,string Value) 

    WritePrivateProfileString(Section,Key,Value,this.Path); } //读取INI文件指定 
    public string IniReadValue(string Section,string Key) 

    StringBuilder temp = new StringBuilder(255); 
    int i = GetPrivateProfileString(Section,Key,"",temp,255,this.Path); 
    return temp.ToString(); } 

    } 操作范例: public static SqlConnection MyConnection() 

    string sPath; 
    string ServerName,userId,sPwd,DataName; sPath = GetPath(); 
    IniFile ini = new IniFile(sPath); 
    ServerName = ini.IniReadValue ("Database","server"); 
    userId = ini.IniReadValue ("Database","uid"); 
    sPwd = ini.IniReadValue ("Database","pwd"); 
    DataName = ini.IniReadValue ("Database","database"); 
    string strSql = "server =" + ServerName+";uid ="+ userId +";pwd =;database ="+ DataName; 
        SqlConnection myConn=new SqlConnection(strSql); 
        return myConn; 

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    using System.Collections;
    using System.Collections.Specialized;namespace wuyisky{
    /**//**/
    /**//// <summary> 
    /// IniFiles的类 
    /// </summary> 
    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();
    }
    }
    }
      

  2.   

    Read/Write XML files, Config files, INI files, or the Registry
    By Alvaro Mendez
    http://www.codeproject.com/KB/cs/readwritexmlini.aspx
      

  3.   

    2楼的方法是对的,  C#没有直接操作INI文件的类, 只有采用 传统API 调用来实现了。