## 调用 ```csharp var filePath = "logs/" + DateTime.Now.ToString("yyyyMMdd") + ".log"; //添加日志记录 DoIOFile.Write(filePath, "项目启动了" ); ``` ## 方法 ```csharp /// /// 创建文件或者附加内容 /// /// 要写入的文本 /// 编码方式 /// 文件路径(支持相对路径或绝对路径) /// 附加还是全新写入 public static bool Write(string Data, string filePath="", bool IsAppend = true, string Encode = "UTF-8") { filePath = string.IsNullOrEmpty(filePath) ? "logs/" + DateTime.Now.ToString("yyyyMMdd") + ".log" : Encode; Encode = string.IsNullOrEmpty(Encode) ? "UTF-8" : Encode; Data = DateTime.Now.ToString()+" :" + Data + "\n"; try { //获取文件对象 FileInfo file = new FileInfo(filePath); //判断文件夹是否创建 if (!file.Directory.Exists) { file.Directory.Create(); } //判断文件是否存在 //或者判断文件属性是否只读,是只读的话将只读属性去掉 if (!file.Exists) { using (file.Create()) { } } else if (file.Attributes.ToString().IndexOf("ReadOnly") != -1) { file.IsReadOnly = false; } //将内容覆盖或者追加到文件的最后 using (StreamWriter writer = new StreamWriter(file.FullName, IsAppend, Encoding.GetEncoding(Encode))) { writer.Write(Data); writer.Flush(); } return true; } catch (Exception ex) { Console.Write(ex.Message); return false; } } ``` Loading... ## 调用 ```csharp var filePath = "logs/" + DateTime.Now.ToString("yyyyMMdd") + ".log"; //添加日志记录 DoIOFile.Write(filePath, "项目启动了" ); ``` ## 方法 ```csharp /// <summary> /// 创建文件或者附加内容 /// </summary> /// <param name="Data">要写入的文本</param> /// <param name="Encode">编码方式</param> /// <param name="filePath">文件路径(支持相对路径或绝对路径)</param> /// <param name="IsAppend">附加还是全新写入</param> public static bool Write(string Data, string filePath="", bool IsAppend = true, string Encode = "UTF-8") { filePath = string.IsNullOrEmpty(filePath) ? "logs/" + DateTime.Now.ToString("yyyyMMdd") + ".log" : Encode; Encode = string.IsNullOrEmpty(Encode) ? "UTF-8" : Encode; Data = DateTime.Now.ToString()+" :" + Data + "\n"; try { //获取文件对象 FileInfo file = new FileInfo(filePath); //判断文件夹是否创建 if (!file.Directory.Exists) { file.Directory.Create(); } //判断文件是否存在 //或者判断文件属性是否只读,是只读的话将只读属性去掉 if (!file.Exists) { using (file.Create()) { } } else if (file.Attributes.ToString().IndexOf("ReadOnly") != -1) { file.IsReadOnly = false; } //将内容覆盖或者追加到文件的最后 using (StreamWriter writer = new StreamWriter(file.FullName, IsAppend, Encoding.GetEncoding(Encode))) { writer.Write(Data); writer.Flush(); } return true; } catch (Exception ex) { Console.Write(ex.Message); return false; } } ``` Last modification:December 29, 2023 © Allow specification reprint Support Appreciate the author AliPayWeChat Like If you think my article is useful to you, please feel free to appreciate