C# Txt文本文件读、写处理函数
|
admin
2025年7月20日 19:28
本文热度 70
|
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 编辑过