-1

如果你能帮忙,我正在徘徊。我有一个控制台应用程序,它以字符串 Directory 作为输入。

我想放置一个检查,它允许我检查用户是否输入了一个空字符串我希望系统记录一个错误,例如 ArgumentNullException。

string inputDirectory = "";
private void DoSomething(string inputDirectory)
            {
                try
                {
                    Directory.CreateDirectory(inputDirectory)
                }
                catch (ArgumentNullException e)
                {
                    Log.Error("program failed because the directory supplied was empty", e.Message);
                }
            }

代码就在这些地方。现在我遇到的问题是没有抛出异常。相反,程序假定该目录位于项目的 bin\Debug 文件夹中。如果提供的目录是“”,我不确定我需要做什么来停止程序的执行。我已经完成了 if(inputDirectory == null) 但这没有奏效。有什么建议吗?谢谢,杰特诺。

4

4 回答 4

2

如果提供的目录是“”,我不确定我需要做什么来停止程序的执行。我已经完成了 if(inputDirectory == null) 但这没有奏效。

利用string.IsNullOrEmpty

或者,如果您使用的是 .Net 4.0 或更高版本,您可以使用string.IsNullOrWhiteSpace

 if(string.IsNullOrWhiteSpace(inputDirectory))
 {
    //invalid input
 }

两者,string.IsNullOrEmpty并且string.IsNullOrWhiteSpace会检查空字符串和空字符串。string.IsNullOrWhiteSpace还检查包含所有空格的字符串。

于 2013-12-10T15:45:54.820 回答
2

也许您可以添加一张支票,例如;

string inputDirectory = "";
private void DoSomething(string inputDirectory)
{
    if (String.IsNullOrEmpty(inputDirectory)
        throw new ArgumentNullException();

    try
    {
        Directory.CreateDirectory(inputDirectory)
    }
    catch (ArgumentNullException e)
    {
        Log.Error("program failed because the directory supplied was empty", e.Message);
    }
}
于 2013-12-10T15:46:33.497 回答
1

您需要String.IsNullOrEmpty()用于检查Empty字符串。

方法String.IsNullOrEmpty()检查给定字符串是否为nullEmpty

如果它找到给定String的是null或者Empty然后它返回true

第 1 步:inputDirectory使用 String.IsNullOrEmpty() 方法检查Null 或 Empty。
第 2 步:如果方法返回,则true抛出ArgumentNullExceptionusingthrow关键字。

尝试这个:

            string inputDirectory = "";
            private void DoSomething(string inputDirectory)
            {
                try
                {
                    if(String.IsNullOrEmpty(inputDirectory))
                    throw new ArgumentNullException();
                    Directory.CreateDirectory(inputDirectory)
                }
                catch (ArgumentNullException e)
                {
                    Log.Error("program failed because the directory supplied was empty", e.Message);
                }
            }
于 2013-12-10T15:46:43.643 回答
1

您可以使用String.IsNullOrWhitespace 来检查字符串是空还是空白。

指示指定的字符串是 null、空还是仅包含空白字符。

if (String.IsNullOrWhitespace(inputDirectory))
{
    throw new YourException("WhatEver");
}
于 2013-12-10T15:46:07.743 回答