1. 程式人生 > 其它 >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 { }
}