c# 的一些基本操作或属性

List 去重

var newList = list.Where((x, i) => list.FindIndex(z => z.Name == x.Name) == i).ToList();

http下载文件,不保存到服务器,直接使用浏览器下载

/// <summary>
/// 根据url下载文件
/// </summary>
/// <param name="url">文件url</param>
/// <param name="fileName">文件名</param>
public void GetFileFromNetUrl(string url, string fileName)
{
     Stream stream = null;
     int bytesToRead = 10000;
     byte[] buffer = new Byte[bytesToRead];
     try
     {
         HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(url);
         HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
         if (fileReq.ContentLength > 0)
            fileResp.ContentLength = fileReq.ContentLength;
            stream = fileResp.GetResponseStream();
            var resp = Response;
            resp.ContentType = "application/octet-stream";
            //设置文件名
            resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
            resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
            int length;
            do
            {
             if (resp.IsClientConnected)
                {
                  length = stream.Read(buffer, 0, bytesToRead);
                  resp.OutputStream.Write(buffer, 0, length);
                  resp.Flush();
                  buffer = new Byte[bytesToRead];
                }
              else
               {
                 length = -1;
               }
             } while (length > 0);
         }
    finally
    {
     if (stream != null)
     {
        stream.Close();
     }
   }
}

 

获取网络图片并转换为base64

 private string GetImgBase64(string imgUrl)
 {
      WebRequest request = WebRequest.Create(imgUrl);
      WebResponse response = request.GetResponse();
      Stream s = response.GetResponseStream();
      byte[] data = new byte[1024];
      int length = 0;
      MemoryStream ms = new MemoryStream();
      while ((length = s.Read(data, 0, data.Length)) > 0)
      {
          ms.Write(data, 0, length);
      }
      ms.Seek(0, SeekOrigin.Begin);
      return Convert.ToBase64String(ms.ToArray());
}

判断请求来源

public ActionResult DownloadApp()
{
     //获取客服端请求源
     string agent = Request.UserAgent;
     string[] keywords = { "Android", "iPhone", "iPod", "iPad", "Windows Phone", "MQQBrowser" };
     // CloudWave.Framework.Core.Logging.Logging4net.WriteInfo(agent);
     //排除 Windows 桌面系统           
     //if (!agent.Contains("Windows NT") || (agent.Contains("Windows NT") && agent.Contains("compatible; MSIE 9.0;")))
     var downloadurl = "";
     //判断是微信, 直接响应应用宝地址
     if (agent.ToLower().Contains("micromessenger"))
     {
         //获取配置信息
     }
     //安卓
     else if (agent.ToLower().Contains(keywords[0]))
     {
                
              
     }
     //苹果
     else if(agent.ToLower().Contains(keywords[1].ToLower())|| agent.ToLower().Contains(keywords[2].ToLower()) 
                || agent.ToLower().Contains(keywords[3].ToLower()))
     {
                
              
     }
       return Json(downloadurl);
}

 js encodeURI编码 后面解码

 var str1 = HttpUtility.UrlDecode(Keyword);
 var str2 = Server.HtmlDecode(Keyword);
 var str3 = Server.UrlDecode(Keyword);
 var str4 = Microsoft.JScript.GlobalObject.decodeURIComponent(Keyword);

 参数渲染扩展类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace System {

    /// <summary>
    /// 参数渲染扩展类
    /// </summary>
    public static class LayoutRenderer {

        /// <summary>
        /// 格式化模板参数替换参数项为对应的值的字符串表示
        /// str:模板字符串(例:"Hello {Text}")
        /// </summary>
        /// <param name="str">模板字符串(例:"Hello {Text}")</param>
        /// <param name="jsonValue">对应模板的参数值,json格式(例:"{\"Text\":\"World\"}")</param>
        /// <returns></returns>
        public static string FormatTemplate(this string str, string jsonValue) {
            var jObject = Newtonsoft.Json.JsonConvert.DeserializeObject<Newtonsoft.Json.Linq.JObject>(jsonValue); // (Newtonsoft.Json.Linq.JObject)req.Data;
            if (jObject != null) {
                string name = "", value = "";
                foreach (var item in jObject) {
                    if (item.Value is Newtonsoft.Json.Linq.JValue) {
                        name = item.Key;
                        value = System.Web.HttpUtility.UrlDecode(item.Value.ToString());
                    }
                    str = str.Replace(string.Format("{0}{1}{2}", "{", name, "}"), value);
                }
            }
            return str;
        }

        /// <summary>
        /// 格式化模板参数替换参数项为对应的值的字符串表示
        /// str:模板字符串(例:"Hello {Text}")
        /// </summary>
        /// <param name="str">模板字符串(例:"Hello {Text}")</param>
        /// <param name="objValue">对应模板的参数值对象实例</param>
        /// <returns></returns>
        public static string FormatTemplate<T>(this string str, T objValue) where T : new() {
            if (objValue != null) {
                var type = objValue.GetType();
                var properties = type.GetProperties();
                foreach (var item in properties) {
                    // item.GetValue();
                    var value = item.GetValue(objValue);
                    if (value != null)
                        str = str.Replace(string.Format("{0}{1}{2}", "{", item.Name, "}"), value.ToString());
                }
            }
            return str;
        }

        /// <summary>
        /// 将传入的字符串中间部分字符替换成特殊字符
        /// </summary>
        /// <param name="value">需要替换的字符串</param>
        /// <param name="startLen">前保留长度</param>
        /// <param name="endLen">尾保留长度</param>
        /// <param name="replaceChar">特殊字符</param>
        /// <returns>被特殊字符替换的字符串</returns>
        public static string ReplaceWithSpecialChar(string value, int startLen = 3, int endLen = 4, char specialChar = '*')
        {
            try
            {
                int lenth = value.Length - startLen - endLen;

                string replaceStr = value.Substring(startLen, lenth);

                string specialStr = string.Empty;

                for (int i = 0; i < replaceStr.Length; i++)
                {
                    specialStr += specialChar;
                }

                value = value.Replace(replaceStr, specialStr);
            }
            catch (Exception)
            {
                return value;
            }

            return value;
        }
    }
}

 

posted @ 2018-06-07 15:15  ice.ko  阅读(655)  评论(0编辑  收藏  举报