TXT(純文本)文件是最基礎(chǔ)、最通用的文件格式之一,在編程和系統(tǒng)管理中廣泛應(yīng)用。它不包含任何格式(如字體、顏色等),僅存儲(chǔ)純文本數(shù)據(jù),具有極高的兼容性和靈活性。 在系統(tǒng)/應(yīng)用程序中常常使用txt文檔保存日志記錄,例如:Web服務(wù)器日志、數(shù)據(jù)庫查詢?nèi)罩尽?/span>應(yīng)用程序調(diào)試日志。
跨平臺(tái)兼容:所有操作系統(tǒng)和編程語言原生支持。
輕量高效:無格式開銷,讀寫速度快。
易于處理:可用任何文本編輯器或命令行工具(如cat、grep)操作。
可讀性強(qiáng):人類可直接閱讀和修改。
無結(jié)構(gòu)化支持:需自行解析(如按行、按分隔符拆分)。
無元數(shù)據(jù):無法存儲(chǔ)編碼、創(chuàng)建時(shí)間等額外信息。
安全性低:明文存儲(chǔ)敏感數(shù)據(jù)需額外加密。
調(diào)用方法如下:
(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)內(nèi)置函數(shù)追加寫入
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)內(nèi)置函數(shù)覆蓋寫入
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)、按內(nèi)置函數(shù)方法讀取
public List<string> ReadTxtStrList(string TxtFilePath)
{
string[] RetLine = File.ReadAllLines(TxtFilePath);
return RetLine.ToList<string>();
}
閱讀原文:原文鏈接
該文章在 2025/7/21 10:30:55 編輯過