天天看點

對INI檔案的讀寫和ODBC的讀取

最近公司的伺服器要改公網的IP,我一聽傻了,因為公司的POS系統的IP也要改,伺服器當然沒問題,但在外邊的用戶端就麻煩了。。我總不可能去全國遊一圈來改IP吧。當然,公司不介意我也接受(旅遊全國我也想了不是一天兩天了:)),想想就決定做個軟體修改用戶端的IP就可以了。反正記錄IP的檔案是個INI檔案,由于用戶端用的是SYBASE,而且用ODBC連接配接,本來有個也挺簡單的方法,就是周遊計算機找到這個檔案來修改。但我覺得這樣不爽,是以想通過ODBC找到INI的路徑(在ODBC裡看到有相關的KEY),然後通過對INI的操作修改其中記錄IP的KEY值就可以了。很簡單的一個程式,下面把關鍵代碼寫下,免得下次要做這些操作的時候又要上網到處找.

//讀寫INI的CLASS

using System;

using System.Text;

using System.Runtime.InteropServices;

//using Microsoft.Win32;

namespace updatePosIP

{

 /// <summary>

 /// execINI 的摘要說明。

 /// </summary>

 public class execINI

 {

//  public execINI()

//  {

//   //

//   // TODO: 在此處添加構造函數邏輯

//   //

//  }

  #region the ini file api function

  [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 defVal, StringBuilder retVal, int size, string filePath);

  [DllImport("kernel32")]

  private static extern int GetPrivateProfileString(string section, string key, string defVal, Byte[] retVal, int size, string filePath);

  #endregion

  private string Path;

  public execINI(string filePath)

  {

   this.Path = filePath;

  }

  /** <summary>

        /// 讀取INI檔案

        /// </summary>

        /// <param name="Section">段,格式[]</param>

        /// <param name="Key">鍵</param>

        /// <returns>傳回byte類型的section組或鍵值組</returns>

        public byte[] IniReadValues(string section, string key)

        {

            byte[] temp = new byte[255];

            int i = GetPrivateProfileString(section, key, "", temp, 255, this.Path);

            return temp;

       }

    }

}

//讀取ODBC中的路徑值,如果要修改值找相關的方法就可以了,自己修改一下就行

using System;

using Microsoft.Win32;

namespace updatePosIP

{

 /// <summary>

 /// execODBC 的摘要說明。

 /// </summary>

 public class execODBC

 {

  public execODBC()

  {

   //

   // TODO: 在此處添加構造函數邏輯

   //

  }

  public static string readOdbc(string keyPath)

  {

//   string strOdbc = @"SOFTWARE/ODBC/ODBC.INI";

   RegistryKey rootkey,okey;

   rootkey = Registry.LocalMachine;

            okey = rootkey.OpenSubKey(keyPath);

   if(okey == null) return null;

   return okey.GetValue("DatabaseFile") == null? null:Convert.ToString(okey.GetValue("DatabaseFile"));

  }

 }

}

剩下就是用個FROM調用就可以了。