C#新手诚征C#实例之一(文件及注册表的访问)

Huiz 2003-11-24 12:51:50
我是一个C#新手,在Delpih编程上有点经验。诚征满足以下条件的回复,谢谢!

3、Windows Ini文件的访问
Ini文件的读、写,将Ini的所有段读到ListBox中,将Ini段的所有键读到ListBox中。

4、Windows Registry的访问
Windows Registry的访问,键读写,创建等。

5、自定义文件的访问
格式化的数据文件(文件流)访问的实例。

以上问题,其中3、30分 4、30分 5、40分。
...全文
28 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
gujianxin 2003-11-24
  • 打赏
  • 举报
回复

using System;
using Microsoft.Win32;
//using EII.Lib.StringPack;



namespace EII.Lib.WinNT
{

//状态定义
public enum REG_STATUS
{
OPERATOR_ERR= -1,
FAILED = 0,
ALL_RIGHT = 1
};


/// <summary>
/// 注册表操作
/// </summary>
public class Regsiter
{
/// <summary>
/// 状态表示
/// </summary>
public REG_STATUS m_RegStatus;


#region 常量定义

/// <summary>
/// Software注册项
/// </summary>
private const string SOFTWARE = "Software";
/// <summary>
/// 公司注册项
/// </summary>
private const string EII = "EII";

#endregion


#region 私有处理
/// <summary>
/// 根级目录
/// </summary>
protected RegistryKey RegUser;
/// <summary>
/// 项目目录,所有注册项限在此范围内
/// </summary>
protected RegistryKey RegProject;

/// <summary>
/// 项目名称
/// </summary>
protected string m_pro = "DistanceLearning";

#endregion


/// <summary>
/// 要在注册表下添加的项目名称 HKEY_LOCAL_MACHINE\SoftWare\EII\
/// </summary>
public string Project
{
get {return m_pro;}
set {
if(value != null && value != "")
{
m_pro = value;

Create();

}
}
}




public Regsiter()
{


RegUser = Registry.LocalMachine ;


RegProject = null;

Create();


}

/// <summary>
/// 使用项目名称构建
/// </summary>
/// <param name="ProName">项目名称</param>
public Regsiter(string ProName)
{
Project = ProName;
RegUser = Registry.LocalMachine ;

RegProject = null;

Create();

}

~Regsiter()
{
Close();
if(RegUser != null)
RegUser.Close();
}



public void Close()
{
//关闭
if(RegProject != null)
RegProject.Close();

RegProject = null;

}

/// <summary>
/// 新建公司子键
/// </summary>
protected bool Create()
{
Close();

//已经建立
if(RegProject != null)
{
m_RegStatus = REG_STATUS.FAILED;
return false;
}

try
{
RegistryKey kSoft = RegUser.OpenSubKey(SOFTWARE,true);

if(kSoft == null)
kSoft = RegUser.CreateSubKey(SOFTWARE);

//打开公司主键
RegistryKey kEII = kSoft.OpenSubKey(EII,true);
//空?
if(kEII == null)
kEII = kSoft.CreateSubKey(EII);

//打开项目主键
RegProject = kEII.OpenSubKey(m_pro,true);
//空?
if(RegProject == null)
RegProject = kEII.CreateSubKey(m_pro);
}
//要操作的“注册表项”不存在
catch(System.ArgumentException )
{

m_RegStatus = REG_STATUS.FAILED;
return false;
}
//要操作的“注册表项”已关闭(无法访问关闭的项)。
catch(System.IO.IOException )
{
m_RegStatus = REG_STATUS.FAILED;
return false;
}

//用户没有 RegistryPermission.SetInclude(read, currentKey) 访问权限。
catch(System.Security.SecurityException)
{
m_RegStatus = REG_STATUS.FAILED;
return false;
}
catch(Exception)
{
m_RegStatus = REG_STATUS.FAILED;
return false;
}
m_RegStatus = REG_STATUS.ALL_RIGHT ;

return true;
}

/// <summary>
/// 取注册表内容
/// </summary>
/// <param name="sKey">公司子键下的项目</param>
/// <returns>此项目的值</returns>
public string GetRegKey(string sKey)
{
//没有建立
if(RegProject == null || m_RegStatus != REG_STATUS.ALL_RIGHT )
return null;

string sResult = null;

try
{
sResult = RegProject.GetValue(sKey).ToString();
// sResult = Convert.ToString(RegProject.GetValue(sKey));
}
//要操作的“注册表项”不存在
catch(System.ArgumentException )
{

return null;
}
//要操作的“注册表项”已关闭(无法访问关闭的项)。
catch(System.IO.IOException )
{
return null;
}

//用户没有 RegistryPermission.SetInclude(read, currentKey) 访问权限。
catch(System.Security.SecurityException)
{
return null;
}
catch(Exception)
{
return null;
}

return sResult;
}

/// <summary>
/// 存注册表内容
/// </summary>
/// <param name="sKey">公司子键下的项目</param>
/// <param name="sNewvalue">新建值</param>
/// <returns>true,成功</returns>
public bool SetRegKey(string sKey,string sNewvalue)
{
//没有建立
if(RegProject == null || m_RegStatus != REG_STATUS.ALL_RIGHT)
return false;

try
{
RegProject.SetValue(sKey,sNewvalue);

}
//要操作的“注册表项”不存在
catch(System.ArgumentException )
{

return false;
}
//要操作的“注册表项”已关闭(无法访问关闭的项)。
catch(System.IO.IOException )
{
return false;
}

//用户没有 RegistryPermission.SetInclude(read, currentKey) 访问权限。
catch(System.Security.SecurityException)
{
return false;
}
catch(Exception)
{
return false;
}

return true;
}

}
}
qiuji 2003-11-24
  • 打赏
  • 举报
回复
4.
补充:
using Microsoft.Win32;
qiuji 2003-11-24
  • 打赏
  • 举报
回复
4.Windows Registry的访问
给你一个例子,你可以参考一下:
RegistryKey key1;
key1=Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Internet Explorer\\Extensions",true);
RegistryKey key2;
key2=key1.CreateSubKey(myGuid);
key2.SetValue("Default Visible","Yes");
key2.SetValue("ButtonText","忆秋季系统便利控制 2.0");
key2.SetValue("HotIcon",Application.StartupPath+"\\hot.ico");
key2.SetValue("Icon",Application.StartupPath+"\\common.ico");
key2.SetValue("CLSID","{1FBA04EE-3024-11D2-8F1F-0000F87ABD16}");
key2.SetValue("Exec",Application.ExecutablePath);
key2.Close();
key1.Close();
雪狼1234567 2003-11-24
  • 打赏
  • 举报
回复
using System;
using System.IO;
public class TextFromFile {
private const string FILE_NAME = "MyFile.txt";
public static void Main(String[] args) {
if (!File.Exists(FILE_NAME)) {
return;
}
StreamReader sr = File.OpenText(FILE_NAME);
String input;
while ((input=sr.ReadLine())!=null) {
//input................
}

sr.Close();
}
}


using System;
using System.IO;
public class TextToFile {
private const string FILE_NAME = "MyFile.txt";
public static void Main(String[] args) {
if (File.Exists(FILE_NAME)) {
return;
}
StreamWriter sr = File.CreateText(FILE_NAME);
sr.WriteLine ("字符串");
sr.Close();
}
}
雪狼1234567 2003-11-24
  • 打赏
  • 举报
回复
using Microsoft.Win32;
RegistryKey SoftwareKey=Registry.LocalMachine.OpenSubKey("Software",true);
RegistryKey MovecontKey=SoftwareKey.CreateSubKey("Movecont");//建立
RegistryKey SelfPlaceKey=MovecontKey.CreateSubKey("SelfPlace");//建立
SelfPlaceKey.SetValue("BackColor",(object)BackColor.ToKnownColor());//写
SelfPlaceKey.SetValue("Red",(object)(int)BackColor.R);//红
SelfPlaceKey.SetValue("Green",(object)(int)BackColor.G);//绿
SelfPlaceKey.SetValue("Blue",(object)(int)BackColor.B);//蓝
SelfPlaceKey.SetValue("Width",(object)Width);//宽
SelfPlaceKey.SetValue("Height",(object)Height);//高
SelfPlaceKey.SetValue("X",(object)DesktopLocation.X);//左上角X坐标
SelfPlaceKey.SetValue("Y",(object)DesktopLocation.Y);//左上角Y坐标
SelfPlaceKey.SetValue("WindowState",(object)WindowState.ToString());//左上角Y坐标
qiuji 2003-11-24
  • 打赏
  • 举报
回复
3.Windows Ini文件的访问
请参考:
http://www.csdn.net/Develop/article/17%5C17764.shtm
http://www.zdnet.com.cn/developer/code/story/0,2000081534,39065664,00.htm
雪狼1234567 2003-11-24
  • 打赏
  • 举报
回复
虽然微软早已经建议在WINDOWS中用注册表代替INI文件,但是在实际应用中,INI文件仍然有用武之地,尤其现在绿色软件的流行,越来越多的程序将自己的一些配置信息保存到了INI文件中。

INI文件是文本文件,由若干节(section)组成,在每个带括号的标题下面,是若干个关键词(key)及其对应的值(Value)

  [Section]

  Key=Value
VC中提供了API函数进行INI文件的读写操作,但是微软推出的C#编程语言中却没有相应的方法,下面我介绍一个读写INI文件的C#类并利用该类保存窗体的坐标,当程序再次运行的时候,窗体将显示在上次退出时的位置。

INIFILE类:

using System;

using System.IO;

using System.Runtime.InteropServices;

因为我们需要调用API函数,所以必须创建System.Runtime.InteropServices命名空间以提供可用于访问 .NET 中的 COM 对象和本机 API 的类的集合。

using System.Text;

namespace Ini

{

publicclass IniFile

{

publicstring path; //INI文件名

[DllImport("kernel32")]

privatestaticexternlong WritePrivateProfileString(string section,string key,string val,string filePath);

[DllImport("kernel32")]

privatestaticexternint GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);

//声明读写INI文件的API函数

public IniFile(string INIPath)

{

path = INIPath;

}

//类的构造函数,传递INI文件名

publicvoid IniWriteValue(string Section,string Key,string Value)

{

WritePrivateProfileString(Section,Key,Value,this.path);

}

//写INI文件

publicstring IniReadValue(string Section,string Key)

{

StringBuilder temp = new StringBuilder(255);

int i = GetPrivateProfileString(Section,Key,"",temp,255,this.path);

return temp.ToString();

}

//读取INI文件指定

}

}

调用INIFILE类:

新建一个标准的C# WINDOWS应用程序项目,在窗体中分别增加命名为sect、key、val的三个文本框。

增加如下代码:
 

using Ini; //创建命名空间

//当窗体关闭时保存窗体坐标

privatevoid Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

{

IniFile ini = new IniFile("C:\\test.ini");

ini.IniWriteValue("LOC" ,"x" ,this.Location.X.ToString() );

ini.IniWriteValue("LOC " ,"y" ,this.Location.Y.ToString() );

//ToString方法将数字转换为字符串

}

//当窗体启动时,读取INI文件的值并赋值给窗体

privatevoid Form1_Load(object sender, System.EventArgs e)

{

IniFile ini = new IniFile("C:\\test.ini");

Point p=new Point() ;

if ((ini.IniReadValue ("LOC" ,"x" )!="" ) && (ini.IniReadValue ("LOC" ,"y" )!=""))

//判断返回值,避免第一次运行时为空出错

{

p.X=int.Parse (ini.IniReadValue ("LOC" ,"x" ));

p.Y =int.Parse (ini.IniReadValue ("LOC" ,"y" ));

// int.Parse将字符串转换为int

this.Location =p;

}

}

维她奶 2003-11-24
  • 打赏
  • 举报
回复
up

110,561

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧