项目中小技巧
参数类中参数名的限制条件:
//手机号(参数类) [Required(ErrorMessage = "项目名称不能为空")]//手机号不能为空 [StringLength(11)]//手机号必须是十一位 public string CraftsmanPhone { get; set; }
// 验证码 长度限制6-9字符
[Required]
[MinLength(6), MaxLength(9)]
public string VerificationCode { get; set; }
获取参数的后缀名,判断是否在数组中:
using System.Linq; using System.IO;
string extension = Path.GetExtension(formFiles.FileName);//获取参数的后缀名
string[] blockTypes ={".exe",".ade", ".adp", ".asa", ".ashx", ".asmx", ".asp", ".bas", ".bat", ".cdx", ".cer", ".chm", ".class", ".cmd", ".cnt", ".com", ".config", ".cpl", ".crt", ".csh",".der", ".dll" };
blockTypes.Contains(extension)//判断参数是否在数组里
事物和事物回滚:
//应用场景:当积分表和总积分表,积分表中加了一条数据,总积分表相应的把积分加上,但是再加总积分是失败了,相应的积分表也不应该添加,所以用事物回滚,把之前更改的取消掉!!
using (var tran = DbContext.Database.BeginTransaction())//启动一个新事物
{
try
{
tran.Commit();// 提交当前事务中对数据库所做的所有更改。
} catch (Exception)
{
tran.Rollback();// 放弃当前事务中对数据库所做的所有更改。
throw;//抛出
}
}
json格式和list格式相互转换:
using System.Text.Json.dll List<GjProjectDepartment> departments =JsonSerializer.Deserialize<List<GjProjectDepartment>>(projectVo.ProjectDepartments);//将json转化为 List<GjProjectDepartment>类型的对象
using System.Text.Json.dll string departments =JsonConvert.SerializeObject(ProjectDepartments);//将指定对象转化为 string的字符串
根据正则查询字符串:
System.Text.RegularExpressions.dll Regex reg = new Regex(@"<img.*?src=""(?<src>[^""]*)""[^>]*>", RegexOptions.IgnoreCase);//根据正则匹配图片 MatchCollection mc = reg.Matches(htmlText); //设定要查找的字符串
对文件或者文件夹的日常操作
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace MCRP.DuoMeiTiXJ.API.Service { /// <summary> /// /// </summary> public class OperateFolderServer { /// <summary> /// 在指定目录下创建文件夹 /// </summary> /// <param name="dir"></param> /// <returns></returns> public static bool CreateDirectory(string dir) { try { bool shiFcz = Directory.Exists(dir); if (!shiFcz) { Directory.CreateDirectory(dir); } } catch (Exception) { } return true; } /// <summary> /// 删除文件夹及下面的文件 /// </summary> /// <param name="dir"></param> /// <returns></returns> public static bool DeleteDirectory(string dir) { try { if (Directory.GetFileSystemEntries(dir).Length > 0) { //遍历文件夹中所有文件 foreach (string file in Directory.GetFiles(dir)) { //文件己存在 if (File.Exists(file)) { FileInfo fi = new FileInfo(file); //判断当前文件属性是否是只读 if (fi.Attributes.ToString().IndexOf("ReadyOnly") >= 0) { fi.Attributes = FileAttributes.Normal; } //删除文件 File.Delete(file); } } //删除文件夹 Directory.Delete(dir); } return true; } catch (Exception ex) { return false; } } /// <summary> /// 删除文件 /// </summary> /// <param name="dir"></param> /// <returns></returns> public static bool DeleteFile(string dir) { try { if (File.Exists(dir)) { File.Delete(dir); } return true; } catch { return false; } } /// <summary> /// 修改文件夹名称 /// </summary> /// <returns></returns> public static bool UpdateDirectory(string srcFolderPath,string destFolderPath) { try { if (System.IO.Directory.Exists(srcFolderPath)) { System.IO.Directory.Move(srcFolderPath, destFolderPath); } } catch (Exception) { } return true; } /// <summary> /// 修改文件名称 /// </summary> /// <param name="srcFileName"></param> /// <param name="destFileName"></param> /// <returns></returns> public static bool UpdateFile(string srcFileName,string destFileName) { try { if (System.IO.File.Exists(srcFileName)) { System.IO.File.Move(srcFileName, destFileName); } } catch (Exception) { } return true; } /// <summary> /// 移动文件 /// </summary> /// <param name="oldWenJian"></param> /// <param name="newWenJian"></param> public static void YiDongWJ(string oldWenJian,string newWenJian) { try { System.IO.File.Move(oldWenJian, newWenJian); } catch (Exception ex) { } } } }
获取上传文件的大小:Double avg = Math.Round((Double)file.Length / (Double)1024, 0);
//单位KB long wenJianDx = (int)avg;
获取配置文件中的值
Startup类中ConfigureServices方法
public IServiceProvider ConfigureServices(IServiceCollection services) { services.Configure<LEDPeiZhi>(Configuration.GetSection("LEDPeiZhi")); return new AutofacServiceProvider(container.Build()); }
LEDPeiZhi类
public class LEDPeiZhi { public string LEDUrl1 { get; set; } }
配置文件appsettings.json:
{
"LEDPeiZhi": { "LEDUrl1": "123456" } }
获取值:
private LEDPeiZhi _urls; public LEDPingRepositories(IOptions<LEDPeiZhi> urls) { _urls = urls.Value; } var LEDWidth3 = _urls.LEDUrl1;
字符串中字母的大小转换:
命名空间:using System; 方法:ToLower()--返回转换为小写的此字符串的副本。 ToUpper()--返回转换为大写的此字符串的副本。 实例:string cc='WABC' string bb=cc.ToLower(); 结果:bb='wabc' 实例:string cc='WABCwabc' string bb=cc.ToUpper(); 结果:bb='WABC'
汉字转化拼音:
NUGET包:NPinyin
命名空间:using NPinyin;
汉字转化全部拼音:
/// <summary> /// 汉字转化为拼音 /// </summary> /// <param name="str">汉字</param> /// <returns>全拼</returns> public static string GetPinyin(string str) { var result = ""; if (!string.IsNullOrEmpty(str)) { result = NPinyin.Pinyin.GetPinyin(str)?.Replace(" ", "").ToLower(); } return result; }
汉字转化拼音首字母:
/// <summary> /// 汉字转化为拼音首字母 /// </summary> /// <param name="str">汉字</param> /// <returns>首字母</returns> public static string GetInitials(string str) { var result = ""; if (!string.IsNullOrEmpty(str)) { result = NPinyin.Pinyin.GetInitials(str)?.Trim().ToLower(); } return result;