C#TXT⽂件的读取和写⼊
/// <summary>
/// ⽂件的写⼊
/// </summary>
/// <param name="path">⽂件路径</param>
/// <param name="name">⽂件名称</param>
/// <param name="contents">写⼊⽂件的内容</param>
/// <returns></returns>
public static KeyValuePair<bool, string> CreateFile(string path, string name, string contents)
{
name = path + "\\" + name;
var pair = new KeyValuePair<bool, string>(true, name);
//验证路径是否存在
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
try
{
FileStream fs;
//验证⽂件是否存在,有先清空⽂本内容,然后追加,否则则创建
if (File.Exists(name))
{
ClearTxt(name);
fs = new FileStream(name, FileMode.Append, FileAccess.Write);
}
else
{
fs = new FileStream(name, FileMode.Create, FileAccess.Write);
}
//这⾥注意是默认编码 ANSI,不需要utf-8
using (var sw = new StreamWriter(fs, Encoding.Default))
{
sw.Write(contents);
sw.Close();
}
fs.Close();
}
catch (Exception ex)
{
pair = new KeyValuePair<bool, string>(false, ex.Message);
}
return pair;
}
/
// <summary>
/// 清空⽂本内容
/// </summary>
/// <param name="txtPath"></param>
public static void ClearTxt(string txtPath)
{
using (var stream = File.Open(txtPath, FileMode.OpenOrCreate, FileAccess.Write))
{
stream.Seek(0, SeekOrigin.Begin);
stream.SetLength(0);
stream.Close();
}
}
/// <summary>
/// ⽂件的读取
/// </summary>
/// <param name="path">⽂件指定的路径</param>
/// <returns></returns>
param namepublic static KeyValuePair<bool, List<string>> ReadFile(string path)
{
var pair = new KeyValuePair<bool, List<string>>();
var str = new List<string>();
try
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs, Encoding.Default))
{
while (!sr.EndOfStream)
{
string sLine = sr.ReadLine();
if (sLine.Length < 1)
{
continue;
}
str.Add(sLine);
}
}
}
if (str.Contains(""))
{
str.Add("读取⽂件的内容为空");
pair = new KeyValuePair<bool, List<string>>(false, str);
}
else
{
pair = new KeyValuePair<bool, List<string>>(true, str);
}
}
catch (Exception ex)
{
str.Add(ex.Message);
pair = new KeyValuePair<bool, List<string>>(false, str);
}
return pair;
}
调⽤⽰例:
读取:basCommon.ReadFile("*****路径/")
写⼊:basCommon.CreateFile("*****路径", "⽂件名称.txt", ⽂件内容);

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。