话不多说直接上干货(静态帮助类,亲测可用):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Base.Common.File.LocalFile
{
public class TxtOperation
{
/// <summary>
/// 读取txt文件内容,并返回集合(一行为一个数据)
/// </summary>
/// <param name="Path">文件地址</param>
public static List<String> ReadTxtContents(string Path)
{
StreamReader sr = new StreamReader(Path, Encoding.Default);
List<String> contents = new List<string>();
string lineContent = "";
while ((lineContent = sr.ReadLine()) != null)
{
contents.Add(lineContent);
}
sr.Close();
return contents;
}
/// <summary>
/// 读取txt文件内容,并返回集合(一行为一个数据)
/// </summary>
/// <param name="Path">文件地址</param>
public static string ReadTxtAllContent(string Path)
{
StreamReader sr = new StreamReader(Path, Encoding.Default);
string content = sr.ReadToEnd();
sr.Close();
return content;
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="savePath"></param>
/// <param name="text"></param>
public static void CreateTxtWithText(string savePath, string text)
{
try
{
System.IO.File.WriteAllText(savePath, text);
}
catch (Exception ex)
{
throw;
}
}
/// <summary>
/// 保存文件
/// </summary>
/// <param name="savePath"></param>
/// <param name="text"></param>
public static void CreateTxtWithText(string savePath, List<string> texts)
{
try
{
System.IO.StreamWriter file = new System.IO.StreamWriter(savePath, true);
foreach (var text in texts)
{
//file.Write(text);
file.WriteLine(text);
}
file.Flush();
file.Close();
}
catch (Exception ex)
{
throw;
}
}
}
}