码农-小菜鸟 通过本文主要向大家介绍了c#公共方法,c#常用方法,c#字符串常用方法,c#常用字符串处理方法,c#string类的常用方法等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com
C# 常用公共方法,具体内容如下
1.后台调用weburl
string hostUrl = "http://www.a.com?id=123" ;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(hostUrl);
myReq.Method = "GET";
HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
Stream myStream = HttpWResp.GetResponseStream();
StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
while (-1 != sr.Peek())
{
strBuilder.Append(sr.ReadLine());
}
sr.Close();
myStream.Close();
HttpWResp.Close();
Newtonsoft.Json.Linq.JObject jo = (Newtonsoft.Json.Linq.JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(strBuilder.ToString());
string resCode = jo["ReturnCode"].ToString();
</div>
2.检测输入URL是否合法
/// <summary>
/// 判断网址是否可以访问
/// </summary>
/// <param name="Url"></param>
/// <returns></returns>
protected bool ChkPageUrl(string url)
{
bool result = false;
try
{
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
myHttpWebRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
myHttpWebRequest.Method = "GET";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
if (myHttpWebResponse.StatusCode == HttpStatusCode.OK)
{
result = true;
}
myHttpWebResponse.Close();
}
catch
{
result = false;
}
return result;
}
</div>
3.批量导出
/// <summary>
/// 批量导出
/// </summary>
/// <returns></returns>
public FileResult ExportStu()
{
//创建Excel文件的对象
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
//添加一个sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
int pager_totalcount = (int)Session["pager_totalcount"];
int totalCount = 0;
//获取list数据
List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", pager_totalcount, 1, out totalCount);
//给sheet1添加第一行的头部标题
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
//创建时间 名称 商户订单号 | 交易号 对方 金额(元) 状态
row1.CreateCell(0).SetCellValue("编号");
row1.CreateCell(1).SetCellValue("标题");
row1.CreateCell(2).SetCellValue("内容");
int Width = 256;
sheet1.SetColumnWidth(0, 10 * Width);
sheet1.SetColumnWidth(1, 25 * Width);
sheet1.SetColumnWidth(2, 60 * Width);
if (infoList != null)
{
var list = infoList.OrderByDescending(p => p.ID);
if (list != null)
{
int i = 0;
//将数据逐步写入sheet1各个行
foreach (var item in list)
{
i = i + 1;
NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i);
rowtemp.CreateCell(0).SetCellValue(item.ID.ToString());
rowtemp.CreateCell(1).SetCellValue(item.Title == null ? "" : item.Title.ToString());
rowtemp.CreateCell(2).SetCellValue(item.Content == null ? "" : item.Content.ToString());
}
}
}
// 写入到客户端
System.IO.MemoryStream ms = new System.IO.MemoryStream();
book.Write(ms);
ms.Seek(0, System.IO.SeekOrigin.Begin);
return File(ms, "application/vnd.ms-excel", HttpUtility.UrlEncode("导出", Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
}
</div>
4.批量导入
<input name="file" type="file" id="file" />
<input type="submit" name="Upload" value="上传" />
/// <summary>
/// 批量导入
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult ImportStu()
{
HttpPostedFileBase file = Request.Files["file"];
string FileName;
string savePath;
if (file == null || file.ContentLength <= 0)
{
return Content("<script>alert('上传失败,请选择上传文件!');location.href='/MyTest/MVCPager';</script>");
}
else
{
string filename = Path.GetFileName(file.FileName);
int filesize = file.ContentLength;//获取上传文件的大小单位为字节byte
string fileEx = System.IO.Path.GetExtension(filename);//获取上传文件的扩展名
string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//获取无扩展名的文件名
string FileType = ".xls,.xlsx";//定义上传文件的类型字符串
if (FileType.Contains(".exe"))//EXCEL
{
return Content("<script>alert('上传文件类型格式错误,不允许导入exe格式的文件!');location.href='/MyTest/MVCPager';</script>");
}
FileName = NoFileName + DateTime.Now.ToString("yyyyMMddhhmmss") + fileEx;
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
savePath = Path.Combine(path, FileName);
file.SaveAs(savePath);
if (FileType.Contains(fileEx))//EXCEL
{
string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 8.0";
OleDbConnection conn = new OleDbConnection(strConn);
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
DataSet myDataSet = new DataSet();
try
{
myCommand.Fill(myDataSet, "ExcelInfo");
}
catch (Exception ex)
{
return Content("<script>alert('上传失败," + ex.Message + "!');location.href='/MyTest/MVCPager';</script>");
}
//列顺序 标题 内容
DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
//事物 异常回滚
using (TransactionScope transaction = new TransactionScope())
{
for (int i = 0; i < table.Rows.Count; i++)
{
ArticleEntity model = new ArticleEntity();
model.Title = table.Rows[i][0].ToString();
model.Content = table.Rows[i][1].ToString();
new AchieveDAL.MyTestDAL().AddArticle(model);
}
transaction.Complete();
}
}
return RedirectToAction("MVCPager", "MyTest");
}
}
</div>
5.获取客户端的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;
}
</div>
6.AES对称加密
/// <summary>
/// 对称加密类
/// </summary>
public class AES
{
/// <summary>
//

