TXT(純文本)文件是最基礎、最通用的文件格式之一,在編程和系統管理中廣泛應用。它不包含任何格式(如字體、顏色等),僅存儲純文本數據,具有極高的兼容性和靈活性。 在系統/應用程序中常常使用txt文檔保存日志記錄,例如:Web服務器日志、數據庫查詢日志、應用程序調試日志。
跨平臺兼容:所有操作系統和編程語言原生支持。
輕量高效:無格式開銷,讀寫速度快。
易于處理:可用任何文本編輯器或命令行工具(如cat、grep)操作。
可讀性強:人類可直接閱讀和修改。
無結構化支持:需自行解析(如按行、按分隔符拆分)。
無元數據:無法存儲編碼、創建時間等額外信息。
安全性低:明文存儲敏感數據需額外加密。
調用方法如下:
(1)文件流方式追加寫入
public void AppendWritTxt(string log, string path, bool IsEnterLine = false)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
if (IsEnterLine)
sw.WriteLine(log.ToString());
else
sw.Write(log.ToString());
sw.Flush();
}
}
}
catch (Exception e)
{
string err = e.Message;
}
}
(2)內置函數追加寫入
public void AppendText(string filePath, string content)
{
File.AppendAllText(filePath, content);
}
public void AppendText(string filePath, List<string> strList)
{
File.AppendAllLines(filePath, strList);
}
(3)文本流方式覆蓋寫入
public void CreateWritTxt(string path, string TxtStr, bool IsEnterLine = false)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
if (IsEnterLine)
sw.WriteLine(TxtStr.ToString());
else
sw.Write(TxtStr.ToString());
sw.Flush();
}
}
}
catch (Exception e)
{
string err = e.Message;
}
}
(4)內置函數覆蓋寫入
public void CreateText(string filePath, string content)
{
File.WriteAllText(filePath, content);
}
public void CreateText(string filePath, List<string> strList)
{
File.WriteAllLines(filePath, strList);
}
public void CreateText(string filePath, string[] str)
{
File.WriteAllLines(filePath, str);
}
public void CreateText(string filePath, byte[] str)
{
File.WriteAllBytes(filePath, str);
}
(1)、按文件流程方式讀取
public List<string> ReadTxtList(string FilePath)
{
List<string> RetList = new List<string>();
if (!File.Exists(FilePath)) return null;
string ReatStr = string.Empty;
using (FileStream fs = new FileStream(FilePath, FileMode.Open))
{
using (StreamReader reader = new StreamReader(fs, UnicodeEncoding.GetEncoding("GB2312")))
{
while ((ReatStr = reader.ReadLine()) != null)
{
ReatStr = ReatStr.Trim().ToString();
RetList.Add(ReatStr);
}
reader.Dispose();
fs.Dispose();
}
}
return RetList;
}
(2)、按內置函數方法讀取
public List<string> ReadTxtStrList(string TxtFilePath)
{
string[] RetLine = File.ReadAllLines(TxtFilePath);
return RetLine.ToList<string>();
}
閱讀原文:原文鏈接
該文章在 2025/7/21 10:30:55 編輯過