<c#>ログファイルを作成する
ログファイルを作成するサンプルです。
使い方
// クラスを使用する宣言 ErrorLog:アプリケーションのフォルダの下にさらにフォルダを作ります。 NarcyNote.ClassLog errorlog = new NarcyNote.ClassLog("ErrorLog"); // ログの保存例 errorlog.SaveLog("○○エラー発生);
ログの内容
2022/05/28 09:00:00,○○エラー発生
2022/05/29 09:01:00,○○エラー発生
2022/05/30 09:02:00,○○エラー発生
ログファイル作成クラス
using System; using System.IO; using System.Text; namespace NarcyNote { class ClassLog { private readonly string foldername; public ClassLog(string folder) { this.foldername = folder; } public bool SaveLog(string message) { // LOGファイル保存 string fullpath = Path.Combine( AppDomain.CurrentDomain.SetupInformation.ApplicationBase, foldername + @"\"); //ファイル名をくっつける前にフォルダがなければ作成 if (!Directory.Exists(fullpath)) { Directory.CreateDirectory(fullpath); } StreamWriter sw = null; message = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss") + "," + message; try { // 既にファイルが存在している場合は追加(2個目の引数:true) fullpath += DateTime.Now.ToString("yyyyMMdd") + ".txt"; sw = new StreamWriter( fullpath, true, Encoding.GetEncoding("UTF-8")); sw.WriteLine(message); } catch { Console.WriteLine("SaveLog失敗:" + fullpath); return false; } finally { if (sw != null) { sw.Close(); } } return true; } } }
ご使用に関しては自己責任でよろしくお願い申し上げます。
2020年12月にpaizaラーニングでC#を受講しました。
コメントでアドバイスをいただけると幸いです。
↓ほしい物リスト↓