文本文件处理封装类源代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;

namespace MyQuery.Utils
{
/// <summary>
/// 封装Txt文件处理
/// by 贾世义 2011-5-27
/// </summary>
public static class TxtHelper
{
/// <summary>
/// 加载txt数据到DataSet
/// </summary>
/// <param name="fileName">完整路径txt文件名 以.txt为后缀</param>
/// <param name="encoding">字符类型 默认GBK</param>
/// <param name="split">分割字符</param>
/// <param name="isFirstTitle">首行是否为标题行</param>
/// <returns></returns>
public static DataSet GetDataFromTxt(string fileName, string encoding, char split, bool isFirstTitle)
{
DataSet ds = null;
if (IsTxtFile(fileName) && File.Exists(fileName))
{
DataTable dt = new DataTable();
Encoding ecode;
if (String.IsNullOrEmpty(encoding))
{
ecode = Encoding.GetEncoding("GBK");
}
else
{
ecode = Encoding.GetEncoding(encoding);
}
int i = 0;
string[] lines = File.ReadAllLines(fileName, ecode);
foreach (string line in lines)
{
string[] options = DataHelper.GetStrings(line, split);
if (options != null)
{
//列
if (i == 0)
{
for (int j = 0; j < options.Length; j++)
{
string n = null;
if (isFirstTitle)
{
n = options[j];
}
if (String.IsNullOrEmpty(n))
{
n = j.ToString();
}
dt.Columns.Add(n);
}
i = 1;
if (isFirstTitle)
{
continue;
}
}
else if (options.Length > dt.Columns.Count)
{
for (int j = 0; j < options.Length - dt.Columns.Count; j++)
{
dt.Columns.Add(dt.Columns.Count.ToString());
}
}
//数据
DataRow dr = dt.NewRow();
for (int j = 0; j < options.Length; j++)
{
dr[j] = options[j];
}
dt.Rows.Add(dr);
}
}
if (dt.Rows.Count > 0)
{
ds = new DataSet();
ds.Tables.Add(dt);
}
}
return ds;
}

/// <summary>
/// 是否为Txt读取支持的后缀类型
/// </summary>
/// <param name="fileName">文件名</param>
/// <returns></returns>
public static bool IsTxtFile(string fileName)
{
return !String.IsNullOrEmpty(fileName) &&
(fileName.EndsWith(".txt", StringComparison.CurrentCultureIgnoreCase)
|| fileName.EndsWith(".csv", StringComparison.CurrentCultureIgnoreCase));
}
/// <summary>
/// 读取文本
/// </summary>
/// <param name="fileName">完整文件名</param>
/// <returns></returns>
public static string GetString(string fileName)
{
string result = null;
if (File.Exists(fileName))
{
result = File.ReadAllText(fileName, Encoding.UTF8);
}
return result;
}
/// <summary>
/// 将文本写入文本文件
/// </summary>
/// <param name="name">完整文件名</param>
/// <param name="content">内容</param>
/// <param name="isCover">是否覆盖存在文件</param>
public static void WriteToFile(string name, string content, bool isCover)
{
FileStream fs = null;
try
{
if (!isCover && File.Exists(name))
{
fs = new FileStream(name, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
sw.WriteLine(content);
sw.Flush();
sw.Close();
}
else
{
File.WriteAllText(name, content, Encoding.UTF8);
}
}
finally
{
if (fs != null)
{
fs.Close();
}
}

}
}
}
欢迎访问:http://121.18.78.216 适易查询分析、工作流、内容管理及项目管理演示平台

你可能感兴趣的:(文本文件)