class FileHelper { /// <summary>
/// 檢驗文件路徑是否合法 /// </summary>
/// <param name="path">文件路徑</param>
private static bool CheckPath(string path) { //正確格式:C:\Users\jcx\Desktop\Test.txt
string pattern = @"\w{1}:([\\].+)*.+\.\w{3,}"; Regex rg = new Regex(pattern); return rg.IsMatch(path); } /// <summary>
/// 建立一個新的文本文件 /// </summary>
/// <param name="path">文件路徑</param>
/// <param name="content">寫入到文本的內容</param>
public static void CreateNewTxtFile(string path,string content) { if (!CheckPath(path)) { throw new Exception("文件路徑不合法"); } //存在則刪除
if (File.Exists(path)) { File.Delete(path); } using (FileStream fs=new FileStream (path,FileMode.CreateNew,FileAccess.Write)) { byte[] bt = Encoding.Default.GetBytes(content); fs.Write(bt,0,bt.Length); } //using
} /// <summary>
/// 讀取文本文件 /// </summary>
/// <param name="path">文件路徑</param>
/// <param name="readByte">指定每次讀取字節數</param>
/// <returns>讀取的所有文本內容</returns>
public static string ReadTxtFile(string path,long readByte) { if (!CheckPath(path)) { throw new Exception("文件路徑不合法"); } StringBuilder result = new StringBuilder(); using (FileStream fs=new FileStream (path,FileMode.Open,FileAccess.Read)) { byte[] bt = new byte[readByte]; while (fs.Read(bt,0,bt.Length)>0) //每次只從文件中讀取部分字節數,一點點讀
{ string txt = Encoding.Default.GetString(bt); //解碼轉換成字符串
result.AppendLine(txt); } } //using
return result.ToString(); } } class Program { static void Main(string[] args) { string path = @"C:\Users\jcx\Desktop\Test.txt"; FileHelper.CreateNewTxtFile(path, "好好努力"); string r = FileHelper.ReadTxtFile(path,2); //2個字節爲一個漢字,一個漢字一個漢字的讀
Console.WriteLine(r); } // Main
}