C# 写日志文件

常用方法:

public class FileHelper
{

    /// <summary>
    /// 用得比较多
    /// </summary>
    /// <param name="msg"></param>
    public static void WriteAppend(string msg)
    {
        System.IO.StreamWriter sw = null;
        try
        {
            var fileName = "C:\\temp\\vipsoft.log";
            //判断文件是否存在
            if (!Directory.Exists(fileName))
            {
                Directory.CreateDirectory(fileName);
            }
            sw = File.AppendText(fileName); 
            sw.WriteLine(msg);
            sw.Flush();
            sw.Close();
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            if (sw != null)
            {
                sw.Close();
            }
        }

    }

    private static void Write(string fileName, byte[] bytes)
    {
        FileStream fs = null;
        string filePath = "C:\\temp\\" + fileName + ".ecg";
        Encoding encoder = Encoding.UTF8;
        try
        {

            //判断文件是否存在
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            fs = File.OpenWrite(filePath);
            fs.Position = fs.Length;
            fs.Write(bytes, 0, bytes.Length);
        }
        catch (Exception ex)
        {
            NLogHelper.Error(ex.Message);
        }
        finally
        {
            if (fs != null)
                fs.Close();
        }
    }

    public static void Write(string msg)
    {
        System.IO.FileStream fs = null;
        System.IO.StreamWriter sw = null;
        try
        {
            string time = System.DateTime.Now.ToString();
            var fileName = "C:\\temp\\vipsoft.log";
            string filePath = System.Web.HttpContext.Current.Server.MapPath(fileName);
            fs = new System.IO.FileStream(filePath, System.IO.FileMode.Append);
            sw = new System.IO.StreamWriter(fs, System.Text.Encoding.GetEncoding("utf-8"));
            sw.WriteLine("======================");
            sw.WriteLine(time);
            sw.WriteLine("----------------------");
            sw.WriteLine(msg);
            sw.WriteLine("----------------------");
        }
        catch (Exception e)
        {
            throw e;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
            }
            if (sw != null)
            {
                sw.Close();
            }
        }
    }
}

 

posted @ 2022-07-13 14:26  VipSoft  阅读(244)  评论(0编辑  收藏  举报