c# - 在 C# 中防止用户输入空控制台

标签 c# visual-studio-2010 console-application

您好,我想阻止用户在输入字段中输入任何内容。

我尝试过使用 if else,但在没有输入时控制台不断崩溃。 (对于用户输入和 ldap 地址输入 ==> 我希望它显示“未检测到输入。”并允许用户重新输入用户名)

如果我使用(results == ""),我会得到一个错误:

"Operator '==' cannot be applied to operands of type 'System.DirectoryServices.SearchResult' and 'string'"

有什么办法可以解决这个问题吗?代码如下所示。

从第 16 行开始受影响的代码(对于顶部代码块)

if (results != null)
{
    //Check is account activated
    bool isAccountActived = IsActive(results.GetDirectoryEntry());

    if (isAccountActived) 
        Console.WriteLine(targetUserName + "'s account is active.");
    else 
        Console.WriteLine(targetUserName + "'s account is inactive.");

    //Check is account expired or locked
    bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());

    if (isAccountLocked) 
        Console.WriteLine(targetUserName + "'s account is locked or has expired.");
    else 
        Console.WriteLine(targetUserName + "'s account is not locked or expired.");

    Console.WriteLine("\nEnter bye to exit.");
    Console.WriteLine("Press any key to continue.\n\n");
}                               
else if (results == " ")
{ 
     //no user entered
    Console.WriteLine("No input detected!");
    Console.WriteLine("\nEnter bye to exit.");
    Console.WriteLine("Press any key to continue.\n");
}
else 
{
    //user does not exist
    Console.WriteLine("User not found!");
    Console.WriteLine("\nEnter bye to exit.");
    Console.WriteLine("Press any key to continue.\n");
}

如果有帮助,我已在下面附加了完整的代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Net;
using System.Net.Sockets;
using System.Net.NetworkInformation;
using System.Data.SqlClient;

namespace ConsoleApplication2
{
    class Program
    {
        const String serviceAccountUserName = "mobileuser1";
        const String serviceAccountPassword = "password123$";
        const int UF_LOCKOUT = 0x0010;
        const int UF_PASSWORD_EXPIRED = 0x800000;

        static void Main(string[] args)
        {
            string line;
            Console.WriteLine("Welcome to account validator V1.0.\n"+"Please enter the ldap address to proceed.");
            Console.Write("\nEnter address: ");
            String ldapAddress = Console.ReadLine();
            try
            { 
                if (ldapAddress != null)
                {
                    Console.WriteLine("\nQuerying for users in " + ldapAddress);
                    //start of do-while
                    do
                    {
                        Console.WriteLine("\nPlease enter the user's account name to proceed.");
                        Console.Write("\nUsername: ");
                        String targetUserName = Console.ReadLine();

                        bool isValid = false;

                        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, ldapAddress))
                        {
                            // validate the credentials
                            isValid = pc.ValidateCredentials(serviceAccountUserName, serviceAccountPassword);

                            // search AD data
                            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ldapAddress, serviceAccountUserName, serviceAccountPassword);

                            //create instance fo the directory searcher
                            DirectorySearcher desearch = new DirectorySearcher(entry);

                            //set the search filter
                            desearch.Filter = "(&(sAMAccountName=" + targetUserName + ")(objectcategory=user))";

                            //find the first instance
                            SearchResult results = desearch.FindOne();

                            if (results != null)
                            {

                                //Check is account activated
                                bool isAccountActived = IsActive(results.GetDirectoryEntry());

                                if (isAccountActived) Console.WriteLine(targetUserName + "'s account is active.");

                                else Console.WriteLine(targetUserName + "'s account is inactive.");


                                //Check is account expired or locked
                                bool isAccountLocked = IsAccountLockOrExpired(results.GetDirectoryEntry());

                                if (isAccountLocked) Console.WriteLine(targetUserName + "'s account is locked or has expired.");

                                else Console.WriteLine(targetUserName + "'s account is not locked or expired.");


                                Console.WriteLine("\nEnter bye to exit.");
                                Console.WriteLine("Press any key to continue.\n\n");
                            }
                            else if (results == " ")
                            { 
                                 //no user entered
                                Console.WriteLine("No input detected!");
                                Console.WriteLine("\nEnter bye to exit.");
                                Console.WriteLine("Press any key to continue.\n");
                            }
                            else 
                            {
                                //user does not exist
                                Console.WriteLine("User not found!");
                                Console.WriteLine("\nEnter bye to exit.");
                                Console.WriteLine("Press any key to continue.\n");
                            }

                        }//end of using                          
                    }//end of do 

                    //leave console when 'bye' is entered
                    while ((line = Console.ReadLine()) != "bye");

                }//end of if for ldap statement
                else if (ldapAddress == " ")
                {
                    Console.WriteLine("No input detected.");
                    Console.ReadLine();
                    Console.WriteLine("\nEnter bye to exit.");
                    Console.ReadLine();
                    Console.WriteLine("Press any key to continue.\n");
                    Console.ReadLine();
                }
                else
                {
                    Console.WriteLine("Address not found!");
                    Console.ReadLine();
                    Console.WriteLine("\nEnter bye to exit.");
                    Console.ReadLine();
                    Console.WriteLine("Press any key to continue.\n");
                    Console.ReadLine();
                }

            }//end of try
            catch (Exception e)  
            {
                Console.WriteLine("Exception caught:\n\n" + e.ToString());  
            }
        } //end of main void

        static private bool IsActive(DirectoryEntry de)
        {
            if (de.NativeGuid == null) return false;

            int flags = (int)de.Properties["userAccountControl"].Value;

            return !Convert.ToBoolean(flags & 0x0002);
        }

        static private bool IsAccountLockOrExpired(DirectoryEntry de)
        {
            string attribName = "msDS-User-Account-Control-Computed";
            de.RefreshCache(new string[] { attribName });
            int userFlags = (int)de.Properties[attribName].Value;

            return userFlags == UF_LOCKOUT || userFlags == UF_PASSWORD_EXPIRED;
        }
    }
}

最佳答案

您应该将 ReadLine 放入循环中。

string UserName = "";
do {
    Console.Write("Username: ");
    UserName = Console.ReadLine();
    if (!string.IsNullOrEmpty(UserName)) {
        Console.WriteLine("OK");
    } else {
        Console.WriteLine("Empty input, please try again");
    }
} while (string.IsNullOrEmpty(UserName));

您基本上会一遍又一遍地重复提示,直到用户输入的字符串不再为 null 或空。 最好的方法可能是创建一个新函数来获取非空输入:

private static string GetInput(string Prompt)
{
    string Result = "";
    do {
        Console.Write(Prompt + ": ");
        Result = Console.ReadLine();
        if (string.IsNullOrEmpty(Result)) {
            Console.WriteLine("Empty input, please try again");
        }
    } while (string.IsNullOrEmpty(Result));
    return Result;
}

然后您可以使用该函数来获取输入,例如:

static void Main(string[] args)
{
    GetInput("Username");
    GetInput("Password");
}

结果: enter image description here

关于c# - 在 C# 中防止用户输入空控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29249068/

相关文章:

c# - 可以在开发机器的 web.config 中加密 ConnectionString 并部署在服务器上吗?

asp.net-mvc - 无法获取页脚的程序集版本

c++ - 向线程发出信号以启动特定功能

c++ - 将 BSTR 复制到 char[1024]?

c - 为什么最小化到工具栏并最大化控制台窗口后图形(点)全部被清除,但文本仍然在上面?

c# - 使用基类中的 static void Main() 方法作为程序的入口点

c# - 尝试验证和阅读新闻源/时间线(C# 桌面应用程序)

c# - 将发布数据的路径重写到 WCF 服务

.net - 即使 EF 可以成功连接,Asp.Net Identity 也无法连接到数据库

c# - 如何查看IIS上的站点是否使用https证书运行