程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#基礎知識 >> 處理文本文件的HoverTreeTextHelper類

處理文本文件的HoverTreeTextHelper類

編輯:C#基礎知識
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;
}
}
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved