C# ini/文件/目录 操作方法


#region API函数声明

[DllImport("kernel32")]//返回0表示失败,非0为成功
private static extern long WritePrivateProfileString(string section, string key,
string val, string filePath);

[DllImport("kernel32")]//返回取得字符串缓冲区的长度
private static extern long GetPrivateProfileString(string section, string key,
string def, StringBuilder retVal, int size, string filePath);

#endregion

#region ini文件操作
//读Ini文件
public static string ReadIniData(string Section, string Key, string NoText, string iniFilePath)
{
if (File.Exists(iniFilePath))
{
StringBuilder temp = new StringBuilder(1024);
GetPrivateProfileString(Section, Key, NoText, temp, 1024, iniFilePath);
return temp.ToString();
}
else
{
return String.Empty;
}
}

//写Ini文件
public static bool WriteIniData(string Section, string Key, string Value, string iniFilePath)
{
if (!File.Exists(iniFilePath))
{
//如果不存在该文件,创建它
Utils.WriteFile(iniFilePath, "");
}
long OpStation = WritePrivateProfileString(Section, Key, Value, iniFilePath);
if (OpStation == 0)
{
return false;
}
else
{
return true;
}

}
#endregion

#region 本地文件操作
//读文件
public static string ReadFile(string path)
{
if (File.Exists(path))
{
//如果文件存在
string test = File.ReadAllText(path, Encoding.Default);
return test;
}
else
{
return String.Empty;
}
}

//写文件
public static void WriteFile(string path, string content)
{
//增加,如果没有该文件,创建它再增加
File.AppendAllText(path, content);
}

//创建目录
public static void WriteDir(string path)
{
// Check to see if a directory exists
bool dirExists = Directory.Exists(path);
//目录不存在
if (!dirExists)
Directory.CreateDirectory(path);
}

//删除文件
public static void DelFile(string path)
{
File.Delete(path);
}

#endregion
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值