using System.IO;
using System.Text;
using System.Text.RegularExpressions;
namespace HoverTreeText
{
/// <summary>
/// 文本文件輔助類
/// </summary>
public class HoverTreeTextHelper
{
string _fileName;
Encoding _encodingHoverTree = Encoding.Default;
public Encoding EncodingHoverTree
{
get { return _encodingHoverTree; }
set { _encodingHoverTree = value; }
}
public HoverTreeTextHelper(string fileName)
{
_fileName = fileName;
}
public bool Exists(string str)
{
StreamReader m_sr = new StreamReader(_fileName, _encodingHoverTree);
string m_str = m_sr.ReadToEnd();
m_sr.Close();
return (m_str.IndexOf(str)>=0);
}
public string ReadContent()
{
StreamReader m_sr = new StreamReader(_fileName, _encodingHoverTree);
string m_str = m_sr.ReadToEnd();
m_sr.Close();
return m_str;
}
public bool WriteContent(string content)
{
//using (StreamWriter m_sw = new StreamWriter(_fileName, false, Encoding.Default))
//{
// m_sw.Write(content);
// m_sw.Close();
//}
StreamWriter m_sw = new StreamWriter(_fileName, false, Encoding.Default);
m_sw.Write(content);
m_sw.Close();
return true;
}
/// <summary>
/// 獲取行數(包括空行)
/// </summary>
/// <returns></returns>
public int GetRowCount()
{
StreamReader m_sr = new StreamReader(_fileName, _encodingHoverTree);
string m_str = m_sr.ReadToEnd();
m_sr.Close();
if (m_str == string.Empty)
return 0;
int m_result = GetAppearTimes(m_str, "\r\n");
if (!m_str.EndsWith("\r\n"))
m_result = m_result + 1;
return m_result;
}
int GetAppearTimes(string str1, string str2)
{
Regex ex = new Regex(str2);
return ex.Matches(str1).Count;
}
/// <summary>
/// 獲取非空行數
/// </summary>
/// <returns></returns>
public int GetNotEmptyRowCount()
{
StreamReader m_sr = new StreamReader(_fileName, _encodingHoverTree);
string m_str = m_sr.ReadToEnd();
m_sr.Close();
if (m_str == string.Empty)
return 0;
int m_result;
m_str = Regex.Replace(m_str, @"\r\n\s*\r\n", "\r\n");
m_str = Regex.Replace(m_str, @"^\r\n", "");
m_str = Regex.Replace(m_str, "\r\n$", "");
m_result = GetAppearTimes(m_str, "\r\n");
if (m_str != string.Empty)
m_result = m_result + 1;
return m_result;
}
}
}