Net Core教程

C# 常用公共方法

本文主要是介绍C# 常用公共方法,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

1、文件大小单位格式

/// <summary>
/// 文件大小单位格式(GB/MB/KB/B)
/// </summary>
/// <param name="b"></param>
/// <returns></returns>
public static string FileUnitToString(long b)
{
    const double GB = 1024 * 1024 * 1024;
    const double MB = 1024 * 1024;
    const double KB = 1024;

    if (b / GB >= 1)
    {
        return Math.Round(b / (double)GB, 1) + "GB";
    }

    if (b / MB >= 1)
    {
        return Math.Round(b / (double)MB, 1) + "MB";
    }

    if (b / KB >= 1)
    {
        return Math.Round(b / (double)KB, 1) + "KB";
    }

    return b + "B";
}

2、获取客户端的IP地址

/// <summary>
/// 获取客户端的IP地址
/// </summary>
/// <returns>客户端IP地址</returns>
public static string Get_ClientIP()
{
    string result = string.Empty;
    result = HttpContext.Current.Request.Headers["X-Real-IP"]; //Nginx 为前端时获取IP地址的方法
    if (result != null)
        return result;

    if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)//发出请求的远程主机的IP地址
    {
        result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
    }
    else if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)//判断是否设置代理,若使用了代理
    {
        if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//获取代理服务器的IP
        {
            result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        else
        {
            result = HttpContext.Current.Request.UserHostAddress;
        }
    }
    else
    {
        result = HttpContext.Current.Request.UserHostAddress;
    }
    if (result == "::1")
        result = string.Empty;
    return result;
}

3、日志操作

public static void WriteErorrLog(Exception ex, string message = "")
{
    if (ex == null) return; //ex = null 返回 
    DateTime dt = DateTime.Now; // 设置日志时间 
    string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 时:分:秒 
    string logName = dt.ToString("yyyy-MM-dd"); //日志名称 
    string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日志存放路径 
    string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //路径 + 名称
    try
    {
        FileInfo info = new FileInfo(log);
        if (info.Directory != null && !info.Directory.Exists)
        {
            info.Directory.Create();
        }
        using (StreamWriter write = new StreamWriter(log, true, Encoding.GetEncoding("utf-8")))
        {
            write.WriteLine(time);
            write.WriteLine(ex.Message);
            write.WriteLine("异常信息:" + ex);
            write.WriteLine("异常堆栈:" + ex.StackTrace);
            write.WriteLine("异常简述:" + message);
            write.WriteLine("\r\n----------------------------------\r\n");
            write.Flush();
            write.Close();
            write.Dispose();
        }
    }
    catch { }
}

  

 

这篇关于C# 常用公共方法的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!