(エッセンス)2020年6月26日C#クラスライブラリファイル読み書き操作ヘルプクラス
14939 ワード
using System;
using System.IO;
using System.Text;
namespace Core.Util
{
///
///
///
public class FileHelper
{
#region
///
///
///
///
///
public static bool Exists(string path)
{
return File.Exists(path);
}
///
///
///
///
public static string GetCurrentDir()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
#endregion
#region
///
///
/// : ; ,
///
///
///
public static void WriteTxt(string content, string path)
{
WriteTxt(content, path, null, null);
}
///
///
/// : ; ,
///
///
///
///
public static void WriteTxt(string content, string path, Encoding encoding)
{
WriteTxt(content, path, encoding, null);
}
///
///
/// : , UTF-8
///
///
///
///
public static void WriteTxt(string content, string path, FileMode fileModel)
{
WriteTxt(content, path, Encoding.UTF8, fileModel);
}
///
///
/// :
///
///
///
///
///
public static void WriteTxt(string content, string path, Encoding encoding, FileMode fileModel)
{
WriteTxt(content, path, encoding, (FileMode?)fileModel);
}
///
///
/// :
///
///
///
///
///
private static void WriteTxt(string content, string path, Encoding encoding, FileMode? fileModel)
{
encoding = encoding ?? Encoding.UTF8;
fileModel = fileModel ?? FileMode.Create;
string dir = Path.GetDirectoryName(path);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (FileStream fileStream = new FileStream(path, fileModel.Value))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream, encoding))
{
streamWriter.Write(content);
streamWriter.Flush();
}
}
}
///
///
///
///
/// ( D:\ \a.log)
public static void WriteLog(string msg, string path = @"Log.txt")
{
string content = $"{DateTime.Now.ToCstTime().ToString("yyyy-MM-dd HH:mm:ss")}:{msg}";
WriteTxt(content, $"{GetCurrentDir()}{content}");
}
#endregion
}
}