c# 工具类代码
来源:互联网 发布:经纬度换算坐标软件 编辑:程序博客网 时间:2024/06/05 22:48
1.对文件的操作类,主要就是文流读取操作的一些东西(包括Assetbundle)
FileHelper.cs
using UnityEngine;using System.Collections;using System.IO;using System.Collections.Generic;using System;/// <summary>/// 使用Application.persistentDataPath方式来创建文件,读写Xml文件./// 注Application.persistentDataPath末尾没有“/”符号/// </summary>public class FileHelper: MonoBehaviour{/// <summary>/// 动态创建文件夹./// </summary>/// <returns>The folder.</returns>/// <param name="path">文件创建目录.</param>/// <param name="FolderName">文件夹名(不带符号).</param>public string CreateFolder(string path,string FolderName){string FolderPath = path+FolderName;if(!Directory.Exists(FolderPath)){ Directory.CreateDirectory(FolderPath);} return FolderPath;} /// <summary>/// 创建文件./// </summary>/// <param name="path">完整文件夹路径.</param>/// <param name="name">文件的名称.</param>/// <param name="info">写入的内容.</param>public void CreateFile(string path,string name,string info){//文件流信息StreamWriter sw;FileInfo t = new FileInfo(path+name);if(!t.Exists){//如果此文件不存在则创建sw = t.CreateText();}else{//如果此文件存在则打开sw = t.AppendText();}//以行的形式写入信息sw.WriteLine(info);//关闭流sw.Close();//销毁流sw.Dispose();} /// <summary>/// 读取文件./// </summary>/// <returns>The file.</returns>/// <param name="path">完整文件夹路径.</param>/// <param name="name">读取文件的名称.</param>public ArrayList LoadFile(string path,string name){//使用流的形式读取StreamReader sr =null;try{sr = File.OpenText(path+name);}catch(Exception e){//路径与名称未找到文件则直接返回空return null;}string line;ArrayList arrlist = new ArrayList();while ((line = sr.ReadLine()) != null){//一行一行的读取//将每一行的内容存入数组链表容器中arrlist.Add(line);}//关闭流sr.Close();//销毁流sr.Dispose();//将数组链表容器返回return arrlist;} //写入模型到本地IEnumerator loadassetbundle(string url){WWW w = new WWW(url);yield return w;if (w.isDone){byte[] model = w.bytes;int length = model.Length;//写入模型到本地CreateassetbundleFile(Application.persistentDataPath, "Model.assetbundle", model,length);}}/// <summary>/// 获取文件下所有文件大小/// </summary>/// <param name="filePath"></param>/// <returns></returns>public int GetAllFileSize(string filePath){int sum = 0;if (!Directory.Exists(filePath)){return 0;} DirectoryInfo dti = new DirectoryInfo(filePath); FileInfo[] fi = dti.GetFiles(); foreach (FileInfo f in fi){ sum += Convert.ToInt32(f.Length / 1024);} DirectoryInfo[] di = dti.GetDirectories(); if (di.Length > 0){for (int i = 0; i < di.Length; i++){sum += GetAllFileSize(di[i].FullName);}}return sum;}/// <summary>/// 获取指定文件大小/// </summary>/// <param name="FilePath"></param>/// <param name="FileName"></param>/// <returns></returns>public int GetFileSize(string FilePath, string FileName){int sum = 0;if (!Directory.Exists(FilePath)){return 0;}else{FileInfo Files = new FileInfo(@FilePath + FileName);sum += Convert.ToInt32(Files.Length / 1024);}return sum;}void CreateassetbundleFile(string path, string name, byte[] info, int length){//文件流信息//StreamWriter sw;Stream sw;FileInfo t = new FileInfo(path + "//" + name);if (!t.Exists){//如果此文件不存在则创建sw = t.Create();}else{//如果此文件存在则打开//sw = t.Append();return;}//以行的形式写入信息sw.Write(info, 0, length);//关闭流sw.Close();//销毁流sw.Dispose();}//读取本地AssetBundle文件IEnumerator LoadAssetbundleFromLocal(string path, string name){print("file:///" + path + "/" + name); WWW w = new WWW("file:///"+path + "/" + name); yield return w; if (w.isDone) {Instantiate(w.assetBundle.mainAsset);}} /// <summary>/// 删除文件./// </summary>/// <param name="path">删除完整文件夹路径.</param>/// <param name="name">删除文件的名称.</param>public void DeleteFile(string path, string name){File.Delete(path + name);}/// <summary>/// 删除文件/// </summary>/// <param name="path"></param>/// <param name="filesName"></param>/// <returns></returns>public bool DeleteFiles(string path, string filesName){bool isDelete = false;try{if (Directory.Exists(path)){if (File.Exists(path + "\\" + filesName)){File.Delete(path + "\\" + filesName);isDelete = true;}}}catch{return isDelete;}return isDelete;}2.随机操作类
RandomHelper.cs
using UnityEngine;using System.Collections;/// <summary>/// 随机操作类/// </summary>public class RandomHelper {private static char[] constant = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };/// <summary>/// 字符串随机/// </summary>/// <param name="Length">要随机的位数</param>/// <returns></returns>public string GenerateRandomNumber(int Length){System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);for (int i = 0; i < Length; i++){newRandom.Append(constant[Random.Range(0,62)]);}return newRandom.ToString();}private static char[] constant1 = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };/// <summary>/// 数字随机/// </summary>/// <param name="Length">要随机的位数</param>/// <returns></returns>public string GenerateNumber(int Length){System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10);for (int i = 0; i < Length; i++){newRandom.Append(constant1[Random.Range(0, 10)]);}return newRandom.ToString();}/// <summary>/// 字符串数组随机/// </summary>/// <param name="chars">数组</param>/// <param name="Length">随机的位数</param>/// <returns></returns>public string GetStrRandomSurname(string[] chars, int Length){int count = chars.Length;System.Text.StringBuilder newRandom = new System.Text.StringBuilder(count); for (int i = 0; i < Length; i++){newRandom.Append(chars[Random.Range(0, count)]);}return newRandom.ToString();}/// <summary>/// 字符串*截取/// </summary>/// <param name="str">字符串</param>/// <returns></returns>public string[] getStringToList(string str){return str.Split('*');}}
3.Utils一些集合
using System;using System.IO;using System.Text.RegularExpressions;using System.Windows.Browser;namespace SL_COMMON{ public class Utils { #region String字符串类 /**/ /// <summary> /// 过滤字符 /// </summary> public static string Replace(string strOriginal, string oldchar, string newchar) { if (string.IsNullOrEmpty(strOriginal)) return ""; string tempChar = strOriginal; tempChar = tempChar.Replace(oldchar, newchar); return tempChar; } /**/ /// <summary> /// 过滤非法字符 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ReplaceBadChar(string str) { if (string.IsNullOrEmpty(str)) return ""; string strBadChar, tempChar; string[] arrBadChar; strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\","; arrBadChar = SplitString(strBadChar, ","); tempChar = str; for (int i = 0; i < arrBadChar.Length; i++) { if (arrBadChar[i].Length > 0) tempChar = tempChar.Replace(arrBadChar[i], ""); } return tempChar; } /**/ /// <summary> /// 检查是否含有非法字符 /// </summary> /// <param name="str">要检查的字符串</param> /// <returns></returns> public static bool ChkBadChar(string str) { bool result = false; if (string.IsNullOrEmpty(str)) return result; string strBadChar, tempChar; string[] arrBadChar; strBadChar = "@@,+,',--,%,^,&,?,(,),<,>,[,],{,},/,\\,;,:,\",\"\""; arrBadChar = SplitString(strBadChar, ","); tempChar = str; for (int i = 0; i < arrBadChar.Length; i++) { if (tempChar.IndexOf(arrBadChar[i]) >= 0) result = true; } return result; } /**/ /// <summary> /// 分割字符串 /// </summary> public static string[] SplitString(string strContent, string strSplit) { if (string.IsNullOrEmpty(strContent)) { return null; } int i = strContent.IndexOf(strSplit); if (strContent.IndexOf(strSplit) < 0) { string[] tmp = { strContent }; return tmp; } //return Regex.Split(strContent, @strSplit.Replace(".", @"\."), RegexOptions.IgnoreCase); return Regex.Split(strContent, @strSplit.Replace(".", @"\.")); } /**/ /// <summary> /// string型转换为int型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <returns>转换后的int类型结果.如果要转换的字符串是非数字,则返回-1.</returns> public static int StrToInt(object strValue) { int defValue = -1; if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10)) { return defValue; } string val = strValue.ToString(); string firstletter = val[0].ToString(); if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1) { return defValue; } else if (val.Length == 10 && !IsNumber(firstletter)) { return defValue; } int intValue = defValue; if (strValue != null) { bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString()); if (IsInt) { intValue = Convert.ToInt32(strValue); } } return intValue; } /**/ /// <summary> /// string型转换为int型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的int类型结果</returns> public static int StrToInt(object strValue, int defValue) { if ((strValue == null) || (strValue.ToString() == string.Empty) || (strValue.ToString().Length > 10)) { return defValue; } string val = strValue.ToString(); string firstletter = val[0].ToString(); if (val.Length == 10 && IsNumber(firstletter) && int.Parse(firstletter) > 1) { return defValue; } else if (val.Length == 10 && !IsNumber(firstletter)) { return defValue; } int intValue = defValue; if (strValue != null) { bool IsInt = new Regex(@"^([-]|[0-9])[0-9]*$").IsMatch(strValue.ToString()); if (IsInt) { intValue = Convert.ToInt32(strValue); } } return intValue; } /**/ /// <summary> /// string型转换为时间型 /// </summary> /// <param name="strValue">要转换的字符串</param> /// <param name="defValue">缺省值</param> /// <returns>转换后的时间类型结果</returns> public static DateTime StrToDateTime(object strValue, DateTime defValue) { if ((strValue == null) || (strValue.ToString().Length > 20)) { return defValue; } DateTime intValue; if (!DateTime.TryParse(strValue.ToString(), out intValue)) { intValue = defValue; } return intValue; } /**/ /// <summary> /// 判断给定的字符串(strNumber)是否是数值型 /// </summary> /// <param name="strNumber">要确认的字符串</param> /// <returns>是则返加true 不是则返回 false</returns> public static bool IsNumber(string strNumber) { return new Regex(@"^([0-9])[0-9]*(\.\w*)?$").IsMatch(strNumber); } /**/ /// <summary> /// 检测是否符合email格式 /// </summary> /// <param name="strEmail">要判断的email字符串</param> /// <returns>判断结果</returns> public static bool IsValidEmail(string strEmail) { return Regex.IsMatch(strEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"); } /**/ /// <summary> /// 检测是否符合url格式,前面必需含有http:// /// </summary> /// <param name="url"></param> /// <returns></returns> public static bool IsURL(string url) { return Regex.IsMatch(url, @"^http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$"); } /**/ /// <summary> /// 检测是否符合电话格式 /// </summary> /// <param name="phoneNumber"></param> /// <returns></returns> public static bool IsPhoneNumber(string phoneNumber) { return Regex.IsMatch(phoneNumber, @"^(\(\d{3}\)|\d{3}-)?\d{7,8}$"); } /**/ /// <summary> /// 检测是否符合身份证号码格式 /// </summary> /// <param name="num"></param> /// <returns></returns> public static bool IsIdentityNumber(string num) { return Regex.IsMatch(num, @"^\d{17}[\d|X]|\d{15}$"); } #endregion #region Sql类 /**/ /// <summary> /// 检测是否有Sql危险字符 /// </summary> /// <param name="str">要判断字符串</param> /// <returns>判断结果</returns> public static bool IsSafeSqlString(string str) { return !Regex.IsMatch(str, @"[-|;|,|\/|\(|\)|\[|\]|\}|\{|%|@|\*|!|\']"); } /**/ /// <summary> /// 替换sql语句中的单引号 /// </summary> public static string ReplaceBadSQL(string str) { string str2; if (str == null) { str2 = ""; } else { str = str.Replace("'", "''"); str2 = str; } return str2; } #endregion #region Html类 /**/ /// <summary> /// 返回 HTML 字符串的解码结果 /// </summary> /// <param name="str">字符串</param> /// <returns>解码结果</returns> public static string HtmlDecode(string str) { //str = str.Replace("''", "'"); return HttpUtility.HtmlDecode(str); } /**/ /// <summary> /// 替换html字符 /// </summary> public static string EncodeHtml(string strHtml) { if (strHtml != "") { strHtml = strHtml.Replace(",", "&def"); strHtml = strHtml.Replace("'", "&dot"); strHtml = strHtml.Replace(";", "&dec"); return strHtml; } return ""; } /**/ /// <summary> /// 替换回车换行符为html换行符 /// </summary> public static string StrFormat(string str) { string str2; if (str == null) { str2 = ""; } else { str = str.Replace("\r\n", "<br />"); str = str.Replace("\n", "<br />"); str2 = str; } return str2; } #endregion #region DateTime类 /**/ /// <summary> /// 返回当前服务器时间的 yyyy-MM-dd 日期格式string /// </summary> public static string GetDate() { return DateTime.Now.ToString("yyyy-MM-dd"); } /**/ /// <summary> ///返回当前服务器时间的标准时间格式string HH:mm:ss /// </summary> public static string GetTime() { return DateTime.Now.ToString("HH:mm:ss"); } /**/ /// <summary> /// 返回当前服务器时间的标准时间格式string yyyy-MM-dd HH:mm:ss /// </summary> public static string GetDateTime() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } /**/ /// <summary> /// 返回当前服务器时间的标准时间格式string yyyy-MM-dd HH:mm:ss:fffffff /// </summary> public static string GetDateTimeF() { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fffffff"); } /**/ /// <summary> /// 将string类型的fDateTime转换为formatStr格式的日期类型 /// </summary> public static string GetStandardDateTime(string fDateTime, string formatStr) { DateTime s = Convert.ToDateTime(fDateTime); return s.ToString(formatStr); } /**/ /// <summary> ///将string类型的fDateTime转换为日期类型 yyyy-MM-dd HH:mm:ss /// </sumary> public static string GetStandardDateTime(string fDateTime) { return GetStandardDateTime(fDateTime, "yyyy-MM-dd HH:mm:ss"); } /**/ /// <summary> /// 返回相差的秒数 /// </summary> /// <param name="Time"></param> /// <param name="Sec"></param> /// <returns></returns> public static int StrDateDiffSeconds(string Time, int Sec) { TimeSpan ts = DateTime.Now - DateTime.Parse(Time).AddSeconds(Sec); if (ts.TotalSeconds > int.MaxValue) { return int.MaxValue; } else if (ts.TotalSeconds < int.MinValue) { return int.MinValue; } return (int)ts.TotalSeconds; } /**/ /// <summary> /// 返回相差的分钟数 /// </summary> /// <param name="time"></param> /// <param name="minutes"></param> /// <returns></returns> public static int StrDateDiffMinutes(string time, int minutes) { if (time == "" || time == null) return 1; TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddMinutes(minutes); if (ts.TotalMinutes > int.MaxValue) { return int.MaxValue; } else if (ts.TotalMinutes < int.MinValue) { return int.MinValue; } return (int)ts.TotalMinutes; } /**/ /// <summary> /// 返回相差的小时数 /// </summary> /// <param name="time"></param> /// <param name="hours"></param> /// <returns></returns> public static int StrDateDiffHours(string time, int hours) { if (time == "" || time == null) return 1; TimeSpan ts = DateTime.Now - DateTime.Parse(time).AddHours(hours); if (ts.TotalHours > int.MaxValue) { return int.MaxValue; } else if (ts.TotalHours < int.MinValue) { return int.MinValue; } return (int)ts.TotalHours; } #endregion #region file类 /**/ /// <summary> /// 文件是否存在 /// </summary> /// <param name="filePath">相对路径</param> /// <returns></returns> public static bool FileExists(string filePath) { if (string.IsNullOrEmpty(filePath)) return false; filePath = HttpContext.Current.Server.MapPath(filePath); DirectoryInfo dirInfo = new DirectoryInfo(filePath); if (dirInfo.Exists) return true; return false; } #endregion }}
持续增加中。。。
阅读全文
0 0
- c# 工具类代码
- C#代码搜索工具
- C# 代码生成工具 Millennials
- 【工具】C#代码混淆工具(Dotfuscator)
- VB.Net C#代码转换工具
- 关于VB.Net C#代码转换工具
- 关于VB.Net C#代码转换工具
- [转]VB.net C# 代码转换工具
- VB.Net C#代码转换工具收藏
- C#代码规范检查工具stylecop
- VB.Net C#代码转换工具
- WMICodeCreator:C#产生WMI代码的工具
- VB.Net C#代码转换工具
- C# 静态代码检查工具StyleCop
- C#静态代码检查工具StyleCode -- 初探
- C#和VB.net代码转换工具
- 检查c#代码内存泄露工具-CLR Profiler工具使用
- C#工具类
- heap_sort
- java IO流学习总结
- angular中的增删查
- 每日总结
- 利用有界面游览器爬取人民网微博(火狐)
- c# 工具类代码
- (二)urllib库的基本使用
- Android中使用fresco加载图片
- maven坐标
- java构造器测试总结
- 如何看待阿里巴巴最新的「大中台,小前台」组织架构? 关注问题写回答
- TCP/IP协议栈与数据报封装 (802.3 Ethernet 以太网 802.11 WLAN 无线网 )
- tomcat端口冲突
- virtualbox虚拟机下 Win7开启 host-only