标签: c#

  • C# 判断中文、日文和韩文

    在 C# 中,我们可以使用正则表达式来判断字符串是否包含特定的字符集。本文将展示如何使用正则表达式来判断字符串是否为中文、日文或韩文。

    1. 正则表达式简介

    • 中文字符:匹配 Unicode 范围为 \u4e00-\u9fa5 的字符。
    • 日文字符:匹配 Unicode 范围为 \u3040-\u309F(平假名)、\u30A0-\u30FF(片假名)、\u4E00-\u9FFF(常用汉字)。
    • 韩文字符:匹配 Unicode 范围为 \uac00-\ud7ff 的字符。

    2. 匹配东亚语言

    如果要匹配所有东亚语言(包括中文、日文和韩文),可以使用如下的正则表达式:

    // language: csharp
    @"[\u4E00-\u9fa5\u3040-\u309F\u30A0-\u30FF\uac00-\ud7ff]"

    该正则表达式能够匹配中文、日文和韩文字符,但如果你希望对不同语言进行分类,则需要具体判断。

    3. 判断韩文

    要判断字符串是否为韩文,可以使用以下代码:

    // language: csharp
    if(System.Text.RegularExpressions.Regex.IsMatch(content, @"^[\uac00-\ud7ff]+$"))
    {
        // 如果是韩文
    }

    该正则表达式会检查字符串是否仅包含韩文字符。

    4. 判断日文

    判断字符串是否为日文,代码如下:

    // language: csharp
    if(System.Text.RegularExpressions.Regex.IsMatch(content, @"^[\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF]+$"))
    {
        // 如果是日文
    }
    

    该正则表达式会检查字符串是否仅包含日文字符。

    5. 判断中文

    判断字符串是否为中文字符,可以使用以下代码:

    // language: csharp
    if (System.Text.RegularExpressions.Regex.IsMatch(content, @"^[\u4e00-\u9fa5]+$"))
    {
        // 如果是中文
    }
    

    该正则表达式会检查字符串是否仅包含中文字符。

    6. 示例应用

    通过结合正则表达式,我们可以很方便地在 C# 中进行不同语言的文本检测。以下是完整示例代码:

    // language: csharp
    using System;
    using System.Text.RegularExpressions;
    
    public class LanguageDetection
    {
        public static void Main(string[] args)
        {
            string content = "这是一个测试内容";
    
            // 判断是否为中文
            if (Regex.IsMatch(content, @"^[\u4e00-\u9fa5]+$"))
            {
                Console.WriteLine("这是中文");
            }
            // 判断是否为日文
            else if (Regex.IsMatch(content, @"^[\u3040-\u309F\u30A0-\u30FF\u4E00-\u9FFF]+$"))
            {
                Console.WriteLine("这是日文");
            }
            // 判断是否为韩文
            else if (Regex.IsMatch(content, @"^[\uac00-\ud7ff]+$"))
            {
                Console.WriteLine("这是韩文");
            }
            else
            {
                Console.WriteLine("无法识别的语言");
            }
        }
    }
    

    这段代码会根据内容的语言输出相应的结果。

  • C#数据库连接类

    在使用Dapper时,我们需要自己创建数据库连接,下面类用于创建并打开一个数据库连接。

    // language: csharp
    public class Db
    {
    	private static string connectionString = "Data Source=.;Initial Catalog=Minsu;User Id=sa;Password=123456;Encrypt=False;TrustServerCertificate=False;";
    
    	public static SqlConnection GetConnection()
    	{
    		SqlConnection conn = new SqlConnection(connectionString);
    		conn.Open();
    		return conn;
    	}
    }

    在使用时,记得要放在using中使用。例如:

    // language: csharp
    using(var conn = Db.GetConnection()) 
    {
        // 数据库操作...
    }
  • C# 字典Dictionary.Add(key, value) 与 Dictionary[key]=value的区别

    相同:

    二者都是根据键值(key),在字典中添加新元素(value)的方法

    不同:

    Dictionary.Add(key, value) 方法,如果 Dictionary 中已经有了这个 key ,那么在进行 Add 会在运行时报错;

    Dictionary[key]=value 方法,如果 Dictionary 中已经有了这个key ,新添加的value将替换之前的 value ,即没有时添加,有时则修改替换

    因此,在使用时更加倾向使用 Dictionary[key]=value 方法,可以减少出错,但是使用时也要注意键值是否正确对应。

  • C#  INI-Parser 操作ini文件

    读取:

    var parser = new IniParser.FileIniDataParser();
    IniParser.Model.IniData data = parser.ReadFile($"{System.Windows.Forms.Application.StartupPath}\\config.ini");
    string bkgmusic = data["system"]["bkgmusic"];

    写入:

    var parser = new IniParser.FileIniDataParser();
    IniParser.Model.IniData data = new IniParser.Model.IniData();
    data["system"]["bkgmusic"] = "1";
    parser.WriteFile($"{System.Windows.Forms.Application.StartupPath}\\config.ini", data);

  • C# NPOI读取excel

    在.NET中,我们操作excel一般都是使用NPOI这个组件,它成熟稳定又好用。下面的代码记录了项目中的一段使用NPOI读取excel的功能的实现:

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;
    using NPOI.XSSF.UserModel;
    
    IWorkbook hssfwb;
    using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
    {
        if (fileName.IndexOf(".xlsx") > 0) // 2007版本
            hssfwb = new XSSFWorkbook(fs);
        else // if (fileName.IndexOf(".xls") > 0) // 2003版本
            hssfwb = new HSSFWorkbook(fs); 
    }
    
    ISheet sheet = hssfwb.GetSheetAt(0); // 或 ISheet sheet = hssfwb.GetSheet("Arkusz1");
    for (int row = 1; row <= sheet.LastRowNum; row++)
    {
        if (sheet.GetRow(row) != null) //null is when the row only contains empty cells
        {
            var s = string.Format("Row {0} = {1}", row, sheet.GetRow(row).GetCell(0).StringCellValue);
        }
    }

  • C# 执行CMD命令

    在.NET的项目开发中有时需要调用系统(Windows)命令,可以使用下面的函数来调用:

    private static string InvokeCmd(string cmdArgs)
    {
        string Tstr = "";
        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        p.Start();
        p.StandardInput.WriteLine(cmdArgs);
        p.StandardInput.WriteLine("exit");
        Tstr = p.StandardOutput.ReadToEnd();
        p.Close();
        return Tstr;
    }

    该函数经过项目测试,没有问题。

  • C# 使用TTS播放声音

    C# 使用Windows系统自带的TTS播放声音,以下代码基于.NET Framework4.0

    // 定义成全局的,因为每次创建实例需要一定的时间,会造成播放延迟
    private dynamic spVoice = Activator.CreateInstance(Type.GetTypeFromProgID("SAPI.SpVoice"));
    
    //调用的时候
    this.spVoice.Speak("你好,我是TTS合成语音");
  • C# WinForm设置dataGridView表头字体大小

    C# WinForm中,设置dataGridView控件表头字体的大小:

    var font = new Font(dataGridView1.ColumnHeadersDefaultCellStyle.Font.FontFamily, dataGridView1.ColumnHeadersDefaultCellStyle.Font.Size + 8);
    dataGridView1.ColumnHeadersDefaultCellStyle.Font = font;

    示例

    // 构造函数
    public HomeForm()
    {
            InitializeComponent();
            //奇数行的单元格的背景色为黄绿色
            dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
            var font = new Font(dataGridView1.ColumnHeadersDefaultCellStyle.Font.FontFamily, dataGridView1.ColumnHeadersDefaultCellStyle.Font.Size + 8);
            dataGridView1.ColumnHeadersDefaultCellStyle.Font = font;
            BindCombox();
            BindDataGrid();
            dataGridView1.Columns[0].Width = 300;
            this.dataGridView1.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
    }
  • C# WinForm 自动关闭 定时关闭 MessageBox

    C# WinForm 的开发中,有时需要一个可以自动关闭的弹出框,下面的代码是自动关闭或定时关闭的一个MessageBox的实现:

    public class AutoClosingMessageBox
    {
        System.Threading.Timer _timeoutTimer;
        string _caption;
        DialogResult _result;
        DialogResult _timerResult;
        AutoClosingMessageBox(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
        {
            _caption = caption;
            _timeoutTimer = new System.Threading.Timer(OnTimerElapsed,
                null, timeout, System.Threading.Timeout.Infinite);
            _timerResult = timerResult;
            using (_timeoutTimer)
                _result = MessageBox.Show(text, caption, buttons);
        }
        public static DialogResult Show(string text, string caption, int timeout, MessageBoxButtons buttons = MessageBoxButtons.OK, DialogResult timerResult = DialogResult.None)
        {
            return new AutoClosingMessageBox(text, caption, timeout, buttons, timerResult)._result;
        }
        void OnTimerElapsed(object state)
        {
            IntPtr mbWnd = FindWindow("#32770", _caption); // lpClassName is #32770 for MessageBox
            if (mbWnd != IntPtr.Zero)
                SendMessage(mbWnd, WM_CLOSE, IntPtr.Zero, IntPtr.Zero);
            _timeoutTimer.Dispose();
            _result = _timerResult;
        }
        const int WM_CLOSE = 0x0010;
        [System.Runtime.InteropServices.DllImport("user32.dll", SetLastError = true)]
        static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
        [System.Runtime.InteropServices.DllImport("user32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
    }
    

    用法:

    AutoClosingMessageBox.Show("Text", "Caption", 1000);

    返回值 

    var userResult = AutoClosingMessageBox.Show("Yes or No?", "Caption", 1000, MessageBoxButtons.YesNo);if(userResult == System.Windows.Forms.DialogResult.Yes) {
    // do something}

    也可以通过Nuget安装这个包

    Install-Package AutoClosingMessageBox
  • C#执行DOS命令,返回DOS命令的输出

    使用下面的代码,可以实现C#执行DOS命令,并返回DOS命令的输出:

     /// <summary> 
    /// 执行DOS命令,返回DOS命令的输出 
    /// </summary> 
    /// <param name="dosCommand">dos命令</param> 
    /// <param name="milliseconds">等待命令执行的时间(单位:毫秒), 
    /// 如果设定为0,则无限等待</param> 
    /// <returns>返回DOS命令的输出</returns> 
    public static string Execute(string command, int seconds)
    {
    	string output = ""; //输出字符串 
    	if (command != null && !command.Equals(""))
    	{
    		Process process = new Process();//创建进程对象 
    		ProcessStartInfo startInfo = new ProcessStartInfo();
    		startInfo.FileName = "cmd.exe";//设定需要执行的命令 
    		startInfo.Arguments = "/C " + command;//“/C”表示执行完命令后马上退出 
    		startInfo.UseShellExecute = false;//不使用系统外壳程序启动
    		startInfo.RedirectStandardInput = false;//不重定向输入 
    		startInfo.RedirectStandardOutput = true; //重定向输出 
    		startInfo.CreateNoWindow = true;//不创建窗口 
    		process.StartInfo = startInfo;
    		try
    		{
    			if (process.Start())//开始进程 
    			{
    				if (seconds == 0)
    				{
    					process.WaitForExit();//这里无限等待进程结束 
    				}
    				else
    				{
    					process.WaitForExit(seconds); //等待进程结束,等待时间为指定的毫秒 
    				}
    				output = process.StandardOutput.ReadToEnd();//读取进程的输出 
    			}
    		}
    		catch (Exception ex)
    		{
    			Console.WriteLine(ex.Message);//捕获异常,输出异常信息
    		}
    		finally
    		{
    			if (process != null)
    				process.Close();
    		}
    	}
    	return output;
    }