C#对于字符串的容错处理

本文详细介绍了如何在软件开发中验证用户输入的有效性,包括检查字符串是否为空、判断文件夹是否存在,以及验证输入数据是否符合特定格式(如十六进制)。此外,还展示了如何在TextBox控件中进行字符追加和换行显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

判断字符串是否为空

if (LogFileSavePathText.Text.Trim() == String.Empty)
{
    MessageBox.Show("Please select path which will be save sensor data!", 
         "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

判断文件夹是否存在

if (Directory.Exists(LogFileSavePathText.Text) == false)
{
    MessageBox.Show("Please check if the Save Log Folder path exists", "Waring");
    return;
}

判断数据是0x00~0xFF的正常字符

public bool IsHexadecimal(string str)
{
    const string PATTERN = @"[A-Fa-f0-9]+$";
    return System.Text.RegularExpressions.Regex.IsMatch(str, PATTERN);
}

if (WifiIDText.Text.Trim() == String.Empty)
{
    MessageBox.Show("Please write the Wifi Device ID!", "Error", 
        MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

if (IsHexadecimal(WifiIDText.Text.ToString()) == false)
{
    MessageBox.Show("Please enter the correct hexadecimal format", "Error", 
        MessageBoxButtons.OK, MessageBoxIcon.Error);
    return;
}

if(Convert.ToInt32(WifiIDText.Text, 16) > 255)
{
    MessageBox.Show("The range of Device ID is 0x00~0xFF", "Error", MessageBoxButtons.OK,             
        MessageBoxIcon.Error);
    return;
}

对于TextBox的字符进行追加和换行显示

private void OutStatusLog(string str)
{
    LogText.AppendText(str);
    LogText.ScrollToCaret();
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值