C# 利用 FileInfo 讀寫檔案
阿新 • • 發佈:2020-12-15
技術標籤:C#
C# 利用 FileInfo 讀寫檔案
/// <summary> /// 獲取指定文字檔案中的內容 /// </summary> /// <param name="paht">檔案路徑</param> /// <returns>返回文字內容</returns> private string GetText(string paht) { string result = string.Empty; try { FileInfo file = new FileInfo(paht); result = file.OpenText().ReadToEnd(); return result; } catch (Exception ex) { return result; } } /// <summary> /// 本地建立檔案並寫入 /// </summary> /// <param name="path">寫入路徑</param> /// <param name="text">寫入內容</param> /// <returns></returns> private bool SetText(string path, string text) { try { FileInfo file = new FileInfo(path); // Delete the file if it exists. if (file.Exists) { file.Delete(); } //Create the file. using (FileStream fs = file.Create()) { Byte[] info = new UTF8Encoding(true).GetBytes(text); //Add some information to the file. fs.Write(info, 0, info.Length); } return true; } catch (Exception ex) { return false; } }