编辑
2025-09-29
C#
00

字符串

方法名称 & 描述
**public static int Compare( string strA, string strB )**比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。该方法区分大小写。
**public static int Compare( string strA, string strB, bool ignoreCase )**比较两个指定的 string 对象,并返回一个表示它们在排列顺序中相对位置的整数。但是,如果布尔参数为真时,该方法不区分大小写。
**public static string Concat( string str0, string str1 )**连接两个 string 对象。
**public bool Contains( string value )**返回一个表示指定 string 对象是否出现在字符串中的值。
**public static string Copy( string str )**创建一个与指定字符串具有相同值的新的 String 对象。
**public void CopyTo( int sourceIndex, char[] destination, int destinationIndex, int count )**从 string 对象的指定位置开始复制指定数量的字符到 Unicode 字符数组中的指定位置。
**public bool EndsWith( string value )**判断 string 对象的结尾是否匹配指定的字符串。
**public bool Equals( string value )**判断当前的 string 对象是否与指定的 string 对象具有相同的值。
**public static bool Equals( string a, string b )**判断两个指定的 string 对象是否具有相同的值。
**public static string Format( string format, Object arg0 )**把指定字符串中一个或多个格式项替换为指定对象的字符串表示形式。
**public int IndexOf( char value )**返回指定 Unicode 字符在当前字符串中第一次出现的索引,索引从 0 开始。
**public int IndexOf( string value, int startIndex )**返回指定字符串从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
**public int IndexOfAny( char[] anyOf )**返回某一个指定的 Unicode 字符数组中任意字符在该实例中第一次出现的索引,索引从 0 开始。
**public int IndexOfAny( char[] anyOf, int startIndex )**返回某一个指定的 Unicode 字符数组中任意字符从该实例中指定字符位置开始搜索第一次出现的索引,索引从 0 开始。
**public string Insert( int startIndex, string value )**返回一个新的字符串,其中,指定的字符串被插入在当前 string 对象的指定索引位置。
**public static bool IsNullOrEmpty( string value )**指示指定的字符串是否为 null 或者是否为一个空的字符串。
**public static string Join( string separator, string[] value )**连接一个字符串数组中的所有元素,使用指定的分隔符分隔每个元素。
**public int LastIndexOf( char value )**返回指定 Unicode 字符在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
**public int LastIndexOf( string value )**返回指定字符串在当前 string 对象中最后一次出现的索引位置,索引从 0 开始。
**public string Remove( int startIndex )**移除当前实例中的所有字符,从指定位置开始,一直到最后一个位置为止,并返回字符串。
**public string Remove( int startIndex, int count )**从当前字符串的指定位置开始移除指定数量的字符,并返回字符串。
**public string Replace( char oldChar, char newChar )**把当前 string 对象中,所有指定的 Unicode 字符替换为另一个指定的 Unicode 字符,并返回新的字符串。
**public string Replace( string oldValue, string newValue )**把当前 string 对象中,所有指定的字符串替换为另一个指定的字符串,并返回新的字符串。
**public string[] Split( params char[] separator )**返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。
**public string[] Split( char[] separator, int count )**返回一个字符串数组,包含当前的 string 对象中的子字符串,子字符串是使用指定的 Unicode 字符数组中的元素进行分隔的。int 参数指定要返回的子字符串的最大数目。
**public bool StartsWith( string value )**判断字符串实例的开头是否匹配指定的字符串。
**public char[] ToCharArray()**返回一个带有当前 string 对象中所有字符的 Unicode 字符数组。
**public char[] ToCharArray( int startIndex, int length )**返回一个带有当前 string 对象中所有字符的 Unicode 字符数组,从指定的索引开始,直到指定的长度为止。
**public string ToLower()**把字符串转换为小写并返回。
**public string ToUpper()**把字符串转换为大写并返回。
**public string Trim()**移除当前 String 对象中的所有前导空白字符和后置空白字符。
C#
string a = "a"; string b = "A"; int result = string.Compare(a, b, false);//返回1,0,-1对应>=< Console.WriteLine(result); string c = string.Concat(a, b);//连接两个字符串 Console.WriteLine(c); string d = String.Format("你的姓名{0}", "张三"); bool b1 = string.IsNullOrEmpty(d);//判断是否为空 string t = "今天天气不错!"; int idx = t.IndexOf("天");//第一次出现 Console.WriteLine(idx); int lidx = t.LastIndexOf("天");//最后一次出现 string s = "28CB-B-00001020010620I&S SH COMMISSION BUSINESSCAI WEI GUO (I&S)1000CLSD"; string[] row = s.Split('\t'); string str = " dd "; s = str.Trim();//删除两边的空格 string z = "今天天气不错"; z = z.Replace("天", "*");//查找替换 z = z.Substring(3); //截取字符以index开始截取,取多少个 Console.WriteLine(z); Console.ReadKey();

字符串转义序列

System.Environment.NewLine 换行

转义序列字符名称
'单引号
"双引号
\反斜杠
\0null
\a警报
\bBackspace
\f换页
\n换行
\r回车
\t水平制表符
\v垂直制表符
\uUnicode 转义序列 (UTF-16)
\UUnicode 转义序列 (UTF-32)
\x除长度可变外,Unicode 转义序列与“\u”类似

stringBuilder

StringBuilder 类创建字符串缓冲区,用于在程序执行多个字符串操控时提升性能。

C#
using System.Text; var sb = new StringBuilder(); //建立一个0到9的字符串 for (int i = 0; i < 10; i++) { sb.Append(i.ToString()); } Console.WriteLine(sb); sb[0] = sb[9];//通过索引访问 Console.WriteLine(sb);

日期操作

Date获取此实例的日期部分。
Day获取此实例所表示的日期为该月中的第几天。
DayOfWeek获取此实例所表示的日期是星期几。
DayOfYear获取此实例所表示的日期是该年中的第几天。
Hour获取此实例所表示日期的小时部分。
Kind获取一个值,该值指示由此实例表示的时间是基于本地时间、协调世界时 (UTC),还是两者皆否。
Millisecond获取此实例所表示日期的毫秒部分。
Minute获取此实例所表示日期的分钟部分。
Month获取此实例所表示日期的月份部分。
Now获取一个 DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为本地时间。
Second获取此实例所表示日期的秒部分。
Ticks获取表示此实例的日期和时间的计时周期数。
TimeOfDay获取此实例的当天的时间。
Today获取当前日期。
UtcNow获取一个 DateTime 对象,该对象设置为此计算机上的当前日期和时间,表示为协调通用时间 (UTC)。
Year获取此实例所表示日期的年份部分。

方法

Add(TimeSpan)返回一个新的 DateTime,它将指定 TimeSpan 的值添加到此实例的值上。
AddDays(Double)返回一个新的 DateTime,它将指定的天数加到此实例的值上。
AddHours(Double)返回一个新的 DateTime,它将指定的小时数加到此实例的值上。
AddMilliseconds(Double)返回一个新的 DateTime,它将指定的毫秒数加到此实例的值上。
AddMinutes(Double)返回一个新的 DateTime,它将指定的分钟数加到此实例的值上。
AddMonths(Int32)返回一个新的 DateTime,它将指定的月数加到此实例的值上。
AddSeconds(Double)返回一个新的 DateTime,它将指定的秒数加到此实例的值上。
AddTicks(Int64)返回一个新的 DateTime,它将指定的刻度数加到此实例的值上。
AddYears(Int32)返回一个新的 DateTime,它将指定的年份数加到此实例的值上。
DaysInMonth(Int32, Int32)返回指定年和月中的天数。
FromFileTimeUtc(Int64)将指定的 Windows 文件时间转换为等效的 UTC 时间。
FromOADate(Double)返回与指定的 OLE 自动化日期等效的 DateTime
GetDateTimeFormats()将此实例的值转换为标准日期和时间格式说明符支持的所有字符串表示形式。
IsDaylightSavingTime()指示此 DateTime 实例是否在当前时区的夏时制范围内。
IsLeapYear(Int32)返回指定的年份是否为闰年的指示。
Parse(String)使用当前区域性的约定将日期和时间的字符串表示形式 DateTime 转换为其等效的 。
SpecifyKind(DateTime, DateTimeKind)创建新的 DateTime 对象,该对象具有与指定的 DateTime 相同的刻度数,但是根据指定的 DateTimeKind 值的指示,指定为本地时间或协调世界时 (UTC),或者两者皆否。
Subtract(DateTime)返回一个新的 TimeSpan,从此实例的值中减去指定的日期和时间。
Subtract(TimeSpan)返回一个新的 DateTime,从此实例的值中减去指定持续时间。
ToFileTime()将当前 DateTime 对象的值转换为 Windows 文件时间。
ToFileTimeUtc()将当前 DateTime 对象的值转换为 Windows 文件时间。
ToLocalTime()将当前 DateTime 对象的值转换为本地时间。
ToLongDateString()将当前 DateTime 对象的值转换为其等效的长日期字符串表示形式。
ToLongTimeString()将当前 DateTime 对象的值转换为其等效的长时间字符串表示形式。
ToOADate()将此实例的值转换为等效的 OLE 自动化日期。
ToShortDateString()将当前 DateTime 对象的值转换为其等效的短日期字符串表示形式。
ToShortTimeString()将当前 DateTime 对象的值转换为其等效的短时间字符串表示形式。
ToString()使用当前的区域性格式约定将当前 DateTime 对象的值转换为它的等效字符串表示形式。
C#
DateTime d1 = DateTime.Now; Console.WriteLine(d1.Date); Console.WriteLine(d1.Day); Console.WriteLine(d1.DayOfWeek); Console.WriteLine(d1.DayOfYear); Console.WriteLine(d1.AddDays(10)); Console.WriteLine(d1.AddDays(-10)); Console.WriteLine(d1.AddHours(6)); Console.WriteLine(d1.AddSeconds(10)); DateTime dt1 = DateTime.Now; **DateTime dt2 = new DateTime(2021, 6, 1); TimeSpan ts = dt2 - dt1;** Console.WriteLine("间隔的天数为{0}天", ts.Days);
C#
//计算某年某月的天数 int days = DateTime.DaysInMonth(2017, 2); Console.WriteLine(days.ToString()); //本月的天数 int daysInMonth = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month); Console.WriteLine(daysInMonth.ToString()); //本年的天数 是否是闰年 int daysInYear = DateTime.IsLeapYear(DateTime.Now.Year) ? 366 : 365; Console.WriteLine(daysInYear.ToString()); //本月第一天 DateTime firstDayInMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1); Console.WriteLine(firstDayInMonth.ToString()); //本月的最后一天 DateTime lastDayInMonth = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddMonths(1).AddDays(-1); Console.WriteLine(lastDayInMonth.ToString()); //得到星期几 星期天为7 int dayOfWeek = Convert.ToInt32(DateTime.Now.DayOfWeek) < 1 ? 7 : Convert.ToInt32(DateTime.Now.DayOfWeek); Console.WriteLine(dayOfWeek.ToString()); //本季度第一天 DateTime firsyDayInQuarter = new DateTime(DateTime.Now.Year, DateTime.Now.Month - (DateTime.Now.Month - 1) % 3, 1); Console.WriteLine(firsyDayInQuarter.ToString()); //本季度最后一天 DateTime lastDayInQuarter = firsyDayInQuarter.AddMonths(3).AddDays(-1); Console.WriteLine(lastDayInQuarter.ToString());

运算符

Addition(DateTime, TimeSpan)将指定的时间间隔加到指定的日期和时间以生成新的日期和时间。
Equality(DateTime, DateTime)确定 DateTime 的两个指定的实例是否相等。
GreaterThan(DateTime, DateTime)确定指定的 DateTime 是否晚于另一个指定的 DateTime
GreaterThanOrEqual(DateTime, DateTime)确定一个指定的 DateTime 表示的日期和时间等于还是晚于另一个指定的 DateTime
Inequality(DateTime, DateTime)确定 DateTime 的两个指定的实例是否不等。
LessThan(DateTime, DateTime)确定指定的 DateTime 是否早于另一个指定的 DateTime
LessThanOrEqual(DateTime, DateTime)确定一个指定的 DateTime 表示的日期和时间等于还是早于另一个指定的 DateTime
Subtraction(DateTime, DateTime)将指定的日期和时间与另一个指定的日期和时间相减,返回一个时间间隔。
Subtraction(DateTime, TimeSpan)从指定的日期和时间减去指定的时间间隔,返回新的日期和时间。
C#
//加法 System.TimeSpan tSpan = new System.TimeSpan(1, 14, 2, 1); DateTime dt3 = new DateTime(2022,1,1) + tSpan; Console.WriteLine(dt3);
C#
//减法 System.DateTime date1 = new System.DateTime(2022, 1, 1, 09, 0, 0); System.DateTime date2 = new System.DateTime(2022, 1, 2, 09, 2, 0); var date3 = date2 - date1; Console.WriteLine(date3);

格式化

d 月中的某一天。一位数的日期没有前导零。

dd 月中的某一天。一位数的日期有一个前导零。

ddd 周中某天的缩写名称,在 AbbreviatedDayNames 中定义。

dddd 周中某天的完整名称,在 DayNames 中定义。

M 月份数字。一位数的月份没有前导零。

MM 月份数字。一位数的月份有一个前导零。

MMM 月份的缩写名称,在 AbbreviatedMonthNames 中定义。

MMMM 月份的完整名称,在 MonthNames 中定义。

y 不包含纪元的年份。如果不包含纪元的年份小于 10,则显示不具有前导零的年份。

yy 不包含纪元的年份。如果不包含纪元的年份小于 10,则显示具有前导零的年份。

yyyy 包括纪元的四位数的年份。

gg 时期或纪元。如果要设置格式的日期不具有关联的时期或纪元字符串,则忽略该模式。

h 12 小时制的小时。一位数的小时数没有前导零。

hh 12 小时制的小时。一位数的小时数有前导零。

H 24 小时制的小时。一位数的小时数没有前导零。

HH 24 小时制的小时。一位数的小时数有前导零。

m 分钟。一位数的分钟数没有前导零。

mm 分钟。一位数的分钟数有一个前导零。

s 秒。一位数的秒数没有前导零。

ss 秒。一位数的秒数有一个前导零。

f 秒的小数精度为一位。其余数字被截断。

ff 秒的小数精度为两位。其余数字被截断。

fff 秒的小数精度为三位。其余数字被截断。

ffff 秒的小数精度为四位。其余数字被截断。

fffff 秒的小数精度为五位。其余数字被截断。

ffffff 秒的小数精度为六位。其余数字被截断。

fffffff 秒的小数精度为七位。其余数字被截断。

C#
DateTime dt1 = DateTime.Now; Console.WriteLine(dt1.ToString("yyyyMMddHHmmss"));

C# File类:文件操作

常用方法

方法说明
Exists确定指定的文件是否存在
Create在指定路径中创建文件
WriteAllBytes以字节形式写入
WriteAllLines以字符串形式写入每一行
WriteAllText以字符串形式写入
AppendAllText以字符串形式追加到文本文件
ReadAllBytes以字节形式读取
ReadAllLines以字符串形式读取每一行
ReadAllText以字符串形式读取文本文件
Copy将现有文件复制到新文件
Move将指定文件移到新位置,并提供指定新文件名的选项
Delete删除指定的文件,如果指定文件不存在,则不引起异常

File 类是静态类,所提供的类成员也是静态的,调用其类成员直接使用 File 类的名称调用即可。

C#
FileInfo file = new FileInfo("./a.txt");
C#
if(File.Exists("./a1.txt")) { string msg = File.ReadAllText("./a.txt"); Console.WriteLine(msg); } else { Console.WriteLine("没有找到相应文件"); }
C#
//读取一个文件 string msg= File.ReadAllText("./a.txt"); Console.WriteLine(msg);

写文件

C#
string str = "这是要输入的内容文本"; string path = "./b.txt"; //表示以 Default (默认格式:ANSI)的类型赋值给字节数组变量 byte[] buffer = System.Text.Encoding.Default.GetBytes(str); File.WriteAllBytes(path, buffer); Console.WriteLine("写入成功");//输出
C#
string str = "这是要输入的内容文本"; string path = "./b.txt"; File.WriteAllText(path,str); Console.WriteLine("写入成功");//输出
C#
string str = "新的内容追加到最后!"; string path = "./b.txt"; File.AppendAllText(path,str); Console.WriteLine("追加写入成功");//输出
C#
string msg = "追加内容"; string path = "./a.txt"; File.AppendAllText(path,msg); string[] strings = { "a", "b", "c" }; File.AppendAllLines(path, strings); Console.WriteLine("追加成功");
C#
try { string str = "这是一个测试文本"; string path = "./a.txt"; byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str); File.WriteAllBytes(path, bytes); Console.WriteLine("写入文件成功!"); } catch(Exception ex) { //错误日志 }

删除一个文件

C#
string path = ".\a.txt"; if (File.Exists(path)) { File.Delete(path); Console.WriteLine("删除成功.");//输出 } else { Console.WriteLine("未找到" + Path.GetFileName(path) + "文件,删除失败."); }
属性或方法作用
DateTime GetCreationTime(string path)返回指定文件或目录的创建日期和时间
DateTime GetLastAccessTime(string path)返回上次访问指定文件或目录的日期和时间
DateTime GetLastWriteTime(string path)返回上次写入指定文件或目录的日期和时间
void SetCreationTime(string path, DateTime creationTime)设置创建该文件的日期和时间
void SetLastAccessTime(string path, DateTime lastAccessTime)设置上次访问指定文件的日期和时间
void SetLastWriteTime(string path, DateTime lastWriteTime)设置上次写入指定文件的日期和时间

读取文件的相应信息

C#
FileAttributes attributes = File.GetAttributes("./a.txt"); if((attributes & FileAttributes.Normal)==FileAttributes.Hidden) { Console.WriteLine("Normal"); } if ((attributes & FileAttributes.Archive) == FileAttributes.Archive) { Console.WriteLine("Archive"); } if ((attributes & FileAttributes.Compressed) == FileAttributes.Compressed) { Console.WriteLine("Compressed"); }

Driveinfo:获取计算机驱动器信息

查看计算机驱动器信息主要包括查看磁盘的空间、磁盘的文件格式、磁盘的卷标等,在 C# 语言中这些操作可以通过 Driveinfo 类来实现。

属性或方法作用
AvailableFreeSpace只读属性,获取驱动器上的可用空闲空间量 (以字节为单位)
DriveFormat只读属性,获取文件系统格式的名称,例如 NTFS 或 FAT32
DriveType只读属性,获取驱动器的类型,例如 CD-ROM、可移动驱动器、网络驱动器或固定驱动器
IsReady只读属性,获取一个指示驱动器是否已准备好的值,True 为准备好了, False 为未准备好
Name只读属性,获取驱动器的名称,例如 C:|
RootDirectory只读属性,获取驱动器的根目录
TotalFreeSpace只读属性,获取驱动器上的可用空闲空间总量 (以字节为单位)
TotalSize只读属性,获取驱动器上存储空间的总大小 (以字节为单位)
VolumeLabel属性, 获取或设置驱动器的卷标
Driveinfo[] GetDrives()静态方法,检索计算机上所有逻辑驱动器的驱动器名称
C#
//遍历驱动器 foreach (var item in DriveInfo.GetDrives()) { Console.WriteLine(item); }; DriveInfo driveInfo = new DriveInfo("C"); Console.WriteLine("驱动器的名称:" + driveInfo.Name); Console.WriteLine("驱动器类型:" + driveInfo.DriveType); Console.WriteLine("驱动器的文件格式:" + driveInfo.DriveFormat); Console.WriteLine("驱动器中可用空间大小:" + driveInfo.TotalFreeSpace); Console.WriteLine("驱动器总大小:" + driveInfo.TotalSize);

Directoryinfo类:文件夹操作

属性或方法作用
Exists只读属性,获取指示目录是否存在的值
Name只读属性,获取 Directorylnfo 实例的目录名称
Parent只读属性,获取指定的子目录的父目录
Root只读属性,获取目录的根部分
void Create()创建目录
DirectoryInfo CreateSubdirectory(string path)在指定路径上创建一个或多个子目录
void Delete()如果目录中为空,则将目录删除
void Delete(bool recursive)指定是否删除子目录和文件,如果 recursive 参数的值为 True,则删除,否则不删除
DirectoryInfo[] GetDirectories()返回当前目录的子目录
DirectoryInfo[] GetDirectories(string searchPattern)返回匹配给定的搜索条件的当前目录
FileInfo[] GetFiles()返回当前目录的文件列表
FileInfo[] GetFiles(string searchPattern)返回当前目录中与给定的搜索模式匹配的文件列表
FileSystemInfo[] GetFileSystemInfos()返回所有文件和目录的子目录中的项
FileSystemInfo[] GetFileSystemInfos(string searchPattern)返回与指定的搜索条件匹配的文件和目录的子目录中的项
void MoveTo(string destDirName)移动 DirectoryInfo 实例中的目录到新的路径

创建文件夹

C#
DirectoryInfo directoryInfo = new DirectoryInfo("D:\\code"); directoryInfo.Create(); directoryInfo.CreateSubdirectory("code1"); directoryInfo.CreateSubdirectory("code2");

遍历目录

C#
DirectoryInfo directoryInfo = new DirectoryInfo("D:\\code"); IEnumerable<DirectoryInfo> dir = directoryInfo.EnumerateDirectories(); foreach (var v in dir) { Console.WriteLine(v.Name); } //遍历文件 foreach (FileInfo fs in di.GetFiles()) { Console.WriteLine(fs.FullName); }

递归遍历目录

C#
private static void forDirectory(string dir) { DirectoryInfo directoryInfo = new DirectoryInfo(dir); IEnumerable<DirectoryInfo> dirs = directoryInfo.EnumerateDirectories(); foreach (var v in dirs) { if (v.GetDirectories().Length > 0) { Console.WriteLine(v.Name); forDirectory(v.FullName); } else { Console.WriteLine(v.Name); } } }

读写注册表

要访问注册表,可以使用Microsoft.Win32命名空间中的两个类Registry 和RegistryKey。RegistryKey实例表示一个注册表项,这个类的方法可以浏览子键、创建新键、读取或修改键中的值。换言之,该类可以完成对注册表项进行的所有操作(除了设置键的安全级别之外)。RegistryKey类可以用于完成对注册表的所有操作。Registry是不能实例化的一个类。它的作用只是提供表示顶级键的RegistryKey实例(不同的巢),以便开始在注册表中浏览。Registry是通过静态属性来提供这些实例的,这些属性共有7个,分别是ClassesRoot、CurrentConfig、CurrentUser、DynData、LocalMachine、PerformanceData和 Users。

  • Registry类封装了注册表的七个基本主键:

    Registry.ClassesRoot 对应于HKEY_CLASSES_ROOT主键 Registry.CurrentUser 对应于HKEY_CURRENT_USER主键 Registry.LocalMachine 对应于 HKEY_LOCAL_MACHINE主键 Registry.User 应于 HKEY_USER主键 Registry.CurrentConfig 对应于HEKY_CURRENT_CONFIG主键 Registry.DynDa 对应于HKEY_DYN_DATA主键 Registry.PerformanceData 对应于HKEY_PERFORMANCE_DATA主键

RegistryKey类封装了对注册表的基本操作。包括读、写、删等操作的常用函数:

函数说明
Close关闭该项,如果该项的内容已修改,则将该项刷新到磁盘。
CreateSubKey(String)创建一个新子项或打开一个现有子项以进行写访问。
CreateSubKey(String, RegistryKeyPermissionCheck)使用指定的权限检查选项创建一个新子项或打开一个现有子项以进行写访问。
CreateSubKey(String, RegistryKeyPermissionCheck, RegistryOptions)使用指定的权限检查和注册表选项,创建或打开一个用于写访问的子项。
CreateSubKey(String, RegistryKeyPermissionCheck, RegistrySecurity)使用指定的权限检查选项和注册表安全性创建一个新子项或打开一个现有子项以进行写访问。
CreateSubKey(String, RegistryKeyPermissionCheck, RegistryOptions, RegistrySecurity)使用指定的权限检查选项、注册表选项和注册表安全性,创建或打开一个用于写访问的子项。
DeleteSubKey(String)删除指定的子项。
DeleteSubKey(String, Boolean)删除指定的子项,并指定在找不到该子项时是否引发异常。
DeleteSubKeyTree(String)递归删除子项和任何子级子项。
DeleteSubKeyTree(String, Boolean)以递归方式删除指定的子项和任何子级子项,并指定在找不到子项时是否引发异常。
DeleteValue(String)从此项中删除指定值。
DeleteValue(String, Boolean)从此项中删除指定的值,并指定在找不到该值时是否引发异常。
Dispose释放由 RegistryKey 类的当前实例占用的所有资源。
Flush将指定的打开注册表项的全部特性写到注册表中。
FromHandle(SafeRegistryHandle)根据指定的句柄创建注册表项。
FromHandle(SafeRegistryHandle, RegistryView)利用指定的句柄和注册表视图设置创建注册表项。
GetAccessControl()返回当前注册表项的访问控制安全性。
GetAccessControl(AccessControlSections)返回当前注册表项的访问控制安全性的指定部分。
GetSubKeyNames检索包含所有子项名称的字符串数组。
GetValue(String)检索与指定名称关联的值。 如果注册表中不存在名称/值对,则返回 null。
GetValue(String, Object)检索与指定名称关联的值。 如果未找到名称,则返回您提供的默认值。
GetValue(String, Object, RegistryValueOptions)检索与指定的名称和检索选项关联的值。 如果未找到名称,则返回您提供的默认值。
GetValueKind检索与指定名称关联的值的注册表数据类型。
GetValueNames检索包含与此项关联的所有值名称的字符串数组。
OpenBaseKey打开一个新的 RegistryKey,它使用指定的视图在本地计算机上表示请求的项。
OpenRemoteBaseKey(RegistryHive, String)打开一个新的 RegistryKey,它表示远程计算机上的请求的项。
OpenRemoteBaseKey(RegistryHive, String, RegistryView)打开一个新的注册表项,它使用指定的视图在远程计算机上表示请求的项。
OpenSubKey(String)以只读方式检索子项。
OpenSubKey(String, RegistryKeyPermissionCheck)检索指定的子项以进行读取或读/写访问。
OpenSubKey(String, Boolean)检索指定的子项,并指定是否将写访问权限应用于该项。
OpenSubKey(String, RegistryKeyPermissionCheck, RegistryRights)检索指定的子项以进行读取或读/写访问,请求指定的访问权限。
SetAccessControl向现有注册表项应用 Windows 访问控制安全性。
SetValue(String, Object)设置指定的名称/值对。
SetValue(String, Object, RegistryValueKind)使用指定的注册表数据类型设置注册表项中的名称/值对的值。
C#
using Microsoft.Win32; RegistryKey localMachine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Default); RegistryKey microsoft = localMachine.OpenSubKey(@"Software\Microsoft", true); microsoft.CreateSubKey("MySoft"); //创建节点 RegistryKey mySoft = microsoft.OpenSubKey("MySoft", true); //设置值 mySoft.SetValue("Name", "TEST"); Console.WriteLine(mySoft.GetValue("Name")); Console.ReadKey();

注意:这个需要权限

字符串解析为数据值

C#
#region 转换为long /// <summary> /// 将object转换为long,若转换失败,则返回0。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static long ParseToLong(this object obj) { try { return long.Parse(obj.ToString()); } catch { return 0L; } } /// <summary> /// 将object转换为long,若转换失败,则返回指定值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static long ParseToLong(this string str, long defaultValue) { try { return long.Parse(str); } catch { return defaultValue; } } #endregion #region 转换为int /// <summary> /// 将object转换为int,若转换失败,则返回0。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static int ParseToInt(this object str) { try { return Convert.ToInt32(str); } catch { return 0; } } /// <summary> /// 将object转换为int,若转换失败,则返回指定值。不抛出异常。 /// null返回默认值 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static int ParseToInt(this object str, int defaultValue) { if (str == null || str.ToString() == "") { return defaultValue; } try { return Convert.ToInt32(str); } catch { return defaultValue; } } #endregion #region 转换为short /// <summary> /// 将object转换为short,若转换失败,则返回0。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static short ParseToShort(this object obj) { try { return short.Parse(obj.ToString()); } catch { return 0; } } /// <summary> /// 将object转换为short,若转换失败,则返回指定值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static short ParseToShort(this object str, short defaultValue) { try { return short.Parse(str.ToString()); } catch { return defaultValue; } } #endregion #region 转换为demical /// <summary> /// 将object转换为demical,若转换失败,则返回指定值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static decimal ParseToDecimal(this object str, decimal defaultValue) { try { return decimal.Parse(str.ToString()); } catch { return defaultValue; } } /// <summary> /// 将object转换为demical,若转换失败,则返回0。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static decimal ParseToDecimal(this object str) { try { return decimal.Parse(str.ToString()); } catch { return 0; } } #endregion #region 转化为bool /// <summary> /// 将object转换为bool,若转换失败,则返回false。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool ParseToBool(this object str) { try { return bool.Parse(str.ToString()); } catch { return false; } } /// <summary> /// 将object转换为bool,若转换失败,则返回指定值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static bool ParseToBool(this object str, bool result) { try { return bool.Parse(str.ToString()); } catch { return result; } } #endregion #region 转换为float /// <summary> /// 将object转换为float,若转换失败,则返回0。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static float ParseToFloat(this object str) { try { return float.Parse(str.ToString()); } catch { return 0; } } /// <summary> /// 将object转换为float,若转换失败,则返回指定值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static float ParseToFloat(this object str, float result) { try { return float.Parse(str.ToString()); } catch { return result; } } #endregion #region 转换为Guid /// <summary> /// 将string转换为Guid,若转换失败,则返回Guid.Empty。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static Guid ParseToGuid(this string str) { try { return new Guid(str); } catch { return Guid.Empty; } } #endregion #region 转换为DateTime /// <summary> /// 转换为between /// </summary> /// <param name="dateField"></param> /// <param name="d1"></param> /// <param name="d2"></param> /// <returns></returns> public static string ParseToSQLBetween(this string dateField, DateTime? d1, DateTime? d2) { string ret = dateField + ">='" + d1.ParseToString("yyyy-MM-dd 00:00:00") + "' and " + dateField + "<= '" + d2.ParseToString("yyyy-MM-dd 23:59:59") + "'"; return ret; } /// <summary> /// 将string转换为DateTime,若转换失败,则返回日期最小值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static DateTime ParseToDateTime(this string str) { try { if (string.IsNullOrWhiteSpace(str)) { return DateTime.MinValue; } if (str.Contains("-") || str.Contains("/")) { return DateTime.Parse(str); } else { int length = str.Length; switch (length) { case 4: return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture); case 6: return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture); case 8: return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); case 10: return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture); case 12: return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture); case 14: return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); default: return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); } } } catch { return DateTime.MinValue; } } /// <summary> /// 将日期转换为指定的格式 /// </summary> /// <param name="dt"></param> /// <param name="Formater">默认为yyyy-MM-dd HH:mm:ss</param> /// <returns></returns> public static string ParseToString(this DateTime? dt, string Formater = "yyyy-MM-dd HH:mm:ss") { if (dt == null) { return ""; } DateTime d1 = (DateTime)dt; if (d1.Year == 1900) { return ""; } else { return d1.ToString(Formater); } } /// <summary> /// 将日期转换为指定的格式 /// </summary> /// <param name="dt"></param> /// <param name="Formater">默认为yyyy-MM-dd HH:mm:ss</param> /// <returns></returns> public static string ParseToString(this DateTime dt, string Formater = "yyyy-MM-dd HH:mm:ss") { if (dt == null) { return ""; } DateTime d1 = (DateTime)dt; if (d1.Year == 1900) { return ""; } else { return d1.ToString(Formater); } } /// <summary> /// 将字符串转换为日期,如果转换失败返回NULL /// </summary> /// <param name="value"></param> /// <returns></returns> public static DateTime? ParseToNullDateTime(this string value) { DateTime dt; if (DateTime.TryParse(value, out dt)) { return dt; } else { return null; } } /// <summary> /// 将string转换为DateTime,若转换失败,则返回默认值。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static DateTime ParseToDateTime(this string str, DateTime? defaultValue) { try { if (string.IsNullOrWhiteSpace(str)) { return defaultValue.GetValueOrDefault(); } if (str.Contains("-") || str.Contains("/")) { return DateTime.Parse(str); } else { int length = str.Length; switch (length) { case 4: return DateTime.ParseExact(str, "yyyy", System.Globalization.CultureInfo.CurrentCulture); case 6: return DateTime.ParseExact(str, "yyyyMM", System.Globalization.CultureInfo.CurrentCulture); case 8: return DateTime.ParseExact(str, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture); case 10: return DateTime.ParseExact(str, "yyyyMMddHH", System.Globalization.CultureInfo.CurrentCulture); case 12: return DateTime.ParseExact(str, "yyyyMMddHHmm", System.Globalization.CultureInfo.CurrentCulture); case 14: return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); default: return DateTime.ParseExact(str, "yyyyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); } } } catch { return defaultValue.GetValueOrDefault(); } } #endregion #region 转换为string /// <summary> /// 将object转换为string,若转换失败,则返回""。不抛出异常。 /// </summary> /// <param name="str"></param> /// <returns></returns> public static string ParseToString(this object obj) { try { if (obj == null) { return string.Empty; } else { return obj.ToString(); } } catch { return string.Empty; } } public static string ParseToStrings<T>(this object obj) { try { var list = obj as IEnumerable<T>; if (list != null) { return string.Join(",", list); } else { return obj.ToString(); } } catch { return string.Empty; } } #endregion #region 转换为double /// <summary> /// 将object转换为double,若转换失败,则返回0。不抛出异常。 /// </summary> /// <param name="obj"></param> /// <returns></returns> public static double ParseToDouble(this object obj) { try { return double.Parse(obj.ToString()); } catch { return 0; } } /// <summary> /// 将object转换为double,若转换失败,则返回指定值。不抛出异常。 /// </summary> /// <param name="str"></param> /// <param name="defaultValue"></param> /// <returns></returns> public static double ParseToDouble(this object str, double defaultValue) { try { return double.Parse(str.ToString()); } catch { return defaultValue; } } #endregion #region 强制转换类型 /// <summary> /// 强制转换类型 /// </summary> /// <typeparam name="TResult"></typeparam> /// <param name="source"></param> /// <returns></returns> public static IEnumerable<TResult> CastSuper<TResult>(this IEnumerable source) { foreach (object item in source) { yield return (TResult)Convert.ChangeType(item, typeof(TResult)); } } #endregion #region "将字符串转换为16进制" public static byte[] ParseToHexByte(this string hex) { hex = hex.Replace(" ", ""); if ((hex.Length % 2) != 0) hex += " "; byte[] returnBytes = new byte[hex.Length / 2]; for (int i = 0; i < returnBytes.Length; i++) returnBytes[i] = Convert.ToByte(hex.Substring(i * 2, 2), 16); return returnBytes; } #endregion #region "将16进制转换为字符串" public static string ParseToHexString(this byte[] bytes) { string ret = ""; if (bytes != null) { for (int i = 0; i < bytes.Length; i++) { ret += bytes[i].ToString("X2"); } } return ret; } #endregion #region "将数字转换成字母" public static string ParseToAlphabet(this int value) { byte[] array = new byte[1]; array[0] = (byte)(Convert.ToInt32(value)); //ASCII码强制转换二进制 string OptionTitle = Convert.ToString(System.Text.Encoding.ASCII.GetString(array)); return OptionTitle; } #endregion

正则表达式

字符描述
|转义字符,将一个具有特殊功能的字符转义为一个普通字符,或反过来
(pattern)匹配 pattern 并获取这一匹配
(?
)
匹配 pattern 但不获取匹配结果
(?=pattern)正向预查,在任何匹配 pattern 的字符串开始处匹配查找字符串
(?!pattern)负向预查,在任何不匹配 pattern 的字符串开始处匹配查找字符串
xy
[xyz]字符集合。匹配所包含的任意一个字符。例如,‘[abc]’可以匹配“plain”中的‘a’
[^xyz]负值字符集合。匹配未包含的任意字符。例如,‘[^abc]’可以匹配“plain”中的‘p’
[a-z]匹配指定范围内的任意字符。例如,‘[a-z]’可以匹配'a'到'z'范围内的任意小写字母字符
[^a-z]匹配不在指定范围内的任意字符。例如,‘[^a-z]’可以匹配不在‘a’~‘z’'内的任意字符
\B匹配非单词边界
\D匹配一个非数字字符,等价于 [^0-9]
\f匹配一个换页符
\n匹配一个换行符
\r匹配一个回车符
\S匹配任何非空白字符
\t匹配一个制表符
\v匹配一个垂直制表符。等价于 \x0b 和 \cK
\W匹配任何非单词字符。等价于‘[^A-Za-z0-9_]’

正则表达式中表示重复的字符

编 号字 符描 述
1*0次或多次字符
2?0次或1次字符
3+1次或多次字符
4{n}n次字符
5{n,M}n到M次字符
6{n, }n次以上字符

校验

C#
using System.Text.RegularExpressions; var s = "^[0-9]*$";//数字 var m = new Regex(s); var ret= m.IsMatch("3443"); Console.WriteLine(ret); s = "^\\d{2}$";//n位的数字 m = new Regex(s); ret = m.IsMatch("34"); Console.WriteLine(ret); s = "^\\d{6,}$";//至少n位的数字 m = new Regex(s); ret = m.IsMatch("34444"); Console.WriteLine(ret); s = "^[\u4e00-\u9fa5]{0,}$";//汉字 m = new Regex(s); ret = m.IsMatch("中国"); Console.WriteLine(ret); s = "^[A-Za-z0-9]+$";//英文和数字 m = new Regex(s); ret = m.IsMatch("abd9832"); Console.WriteLine(ret); s = "^[A-Za-z]+$";//由26个英文字母组成的字符串 m = new Regex(s); ret = m.IsMatch("abc"); Console.WriteLine(ret); s = @"^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$";//Email地址 m = new Regex(s); ret = m.IsMatch("abc@163.com"); Console.WriteLine(ret); s = @"^(13[0-9]|14[5|7]|15[0|1|2|3|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9])\d{8}$";//手机号码 m = new Regex(s); ret = m.IsMatch("13777772292"); Console.WriteLine(ret); s = @"^\d{15}|\d{18}$";//身份证号(15位、18位数字) m = new Regex(s); ret = m.IsMatch("111010191999229932"); Console.WriteLine(ret); s = @"^[a-zA-Z]\w{5,17}$";//密码(以字母开头,长度在6~18之间,只能包含字母、数字和下划线) m = new Regex(s); ret = m.IsMatch("I0011111"); Console.WriteLine(ret);

Math类

方法描述
Abs取绝对值
Ceiling返回大于或等于指定的双精度浮点数的最小整数值
Floor返回小于或等于指定的双精度浮点数的最大整数值
Equals返回指定的对象实例是否相等
Max返回两个数中较大数的值
Min返回两个数中较小数的值
Sqrt返回指定数字的平方根
Round返回四舍五入后的值
AwayFromZero1舍入到最接近的数字的策略,当数字在两个数字之间的中间时,它将舍入到离零的最接近的数字。
ToEven0舍入到最接近的数字的策略,当数字在两个数字之间的中间时,它将舍入到最接近的偶数。
ToNegativeInfinity3向下定向舍入的策略,结果最接近且不大于无限精确结果。
ToPositiveInfinity4向上定向舍入的策略,结果最接近且不小于无限精确结果。
ToZero2定向向零舍入的策略,结果最接近且数量级不大于无限精确结果。
C#
Console.WriteLine(Math.Round(2.56, MidpointRounding.ToZero));//2 Console.WriteLine(Math.Round(2.1, MidpointRounding.ToEven));//2 Console.WriteLine(Math.Round(2.1, MidpointRounding.ToPositiveInfinity));//3 Console.WriteLine(Math.Ceiling(2.1));//3 Console.WriteLine(Math.Floor(2.6));//2

本文作者:技术老小子

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!