ASP.NET 文件操作类

时间:2023-12-16 09:29:14

1.读取文件

2.写入文件

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml; namespace BigData.Common.File
{
/// <summary>
/// 文件操作类
/// </summary>
public class FileHelper
{
/// <summary>
/// 写入一行数据
/// </summary>
/// <param name="path"></param>
/// <param name="str"></param>
/// <param name="isAppend"></param>
/// <returns></returns>
public static bool WriteLine(string path, string str, bool isAppend = true)
{
try
{
StreamWriter sw = new StreamWriter(path, isAppend);
sw.WriteLine(str);
sw.Flush();
sw.Close();
}
catch (Exception)
{
return false;
} return true;
} /// <summary>
/// 读取文件所有内容
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string ReadAll(string path)
{
string result = string.Empty;
try
{
StreamReader sr = new StreamReader(path);
result = sr.ReadToEnd();
sr.Close();
}
catch (Exception)
{
return string.Empty;
} return result;
} /// <summary>
/// 写入文本
/// </summary>
/// <param name="path"></param>
/// <param name="str"></param>
/// <returns></returns>
public static bool WriteToTxt(string path, string str)
{
try
{
FileStream fs = new FileStream(path, FileMode.Append);
byte[] bs = Encoding.Default.GetBytes(str);
fs.Write(bs, , bs.Length);
fs.Flush();
fs.Close();
}
catch (Exception)
{
return false;
} return true;
} /// <summary>
/// 读取文本
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static string ReadTxt(string path)
{
string result = string.Empty;
try
{
FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
byte[] bs = new byte[fs.Length];
fs.Read(bs, , bs.Length);
result = Encoding.Default.GetString(bs);
fs.Close();
}
catch (Exception)
{
return string.Empty;
} return result;
}
}
}