using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace BrilCommon
{
/* 功能:文本文件读写操作
*/
public static class Txt
{
/// <summary>
/// 读取按行存储数据的文本配置文件
/// </summary>
/// <param name="FileName">路径文件名</param>
/// <param name="KeyName">配置项关键字</param>
/// <param name="defaultvalue">当配置项关键字不存在时的默认值</param>
/// <returns></returns>
public static string Read(string FileName, string KeyName, string defaultvalue = "")
{
try
{
StreamReader sr = new StreamReader(FileName);
string tStr = "";
bool isFind = false;
while (!sr.EndOfStream)
{
tStr = sr.ReadLine();
if (tStr.IndexOf(KeyName) >= 0)
{
tStr = tStr.Replace(KeyName, "");
isFind = true;
break;
}
}
sr.Close();
if (isFind)
{
return tStr;
}
else
{
return defaultvalue;
}
}
catch (Exception ex)
{ throw ex; }
}
/// <summary>
/// 写入按行存储数据的文本配置文件
/// </summary>
/// <param name="FileName">路径文件名</param>
/// <param name="KeyName">配置项关键字</param>
/// <param name="Value">要写入的值</param>
public static void Write(string FileName, string KeyName, string Value)
{
try
{
string strall = "", tStr = "";
bool isFind = false;
int NameStart= FileName.LastIndexOf('\\');
if (NameStart >= 0)
{
string dir = FileName.Substring(0, NameStart);
if (!Directory.Exists(dir))
{ Directory.CreateDirectory(dir); }
}
if (File.Exists(FileName))
{
StreamReader sr = new StreamReader(FileName);
while (!sr.EndOfStream)
{
tStr = sr.ReadLine();
if (tStr.IndexOf(KeyName) >= 0)
{
tStr = KeyName + Value;
isFind = true;
}
strall += tStr + Environment.NewLine;
}
sr.Close();
}
if (!isFind)
{
tStr = KeyName + Value;
strall += tStr;
}
else
{
strall = strall.Substring(0, strall.Length - Environment.NewLine.Length);
}
StreamWriter sw = new StreamWriter(FileName, false);
sw.Write(strall);
sw.Close();
}
catch (Exception ex)
{ throw ex; }
}
/// <summary>
/// 按指定编码格式在文本文件中写入数据
/// </summary>
/// <param name="FileName">路径文件名</param>
/// <param name="Value">文本数据</param>
/// <param name="code">编码</param>
public static void Write(string FileName, string Value, Encoding code)
{
try
{
FileStream fs;
string Dir = FileName.Substring(0, FileName.LastIndexOf('\\'));
if (!Directory.Exists(Dir))
{
Directory.CreateDirectory(Dir);
}
if (!File.Exists(FileName))
{
fs = File.Create(FileName);
}
else
{
fs = new FileStream(FileName, FileMode.Append);
}
StreamWriter sw = new StreamWriter(fs, code);
sw.Write(Value);
sw.Close();
fs.Close();
}
catch (Exception ex)
{ throw ex; }
}
/// <summary>
/// 用ANSI编码向文本中追加字符串
/// </summary>
/// <param name="FileName">路径文件名</param>
/// <param name="Value">文本数据</param>
public static void Write(string FileName, string Value)
{
Write(FileName, Value, Encoding.Default);
}
}
}
文件读写类
最新推荐文章于 2020-01-21 15:17:12 发布