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();
}
}
}
}
}
作者“賈世義”