【问题标题】:C# If else program not recognizing the if statement and only taking the elseC# If else 程序不识别 if 语句,只接受 else
【发布时间】:2018-08-21 07:33:08
【问题描述】:

您好我有以下代码,我面临的问题是无论文件夹是否存在它仍然继续发送电子邮件而不是忽略发送它。

我可以改变什么来让它工作。

    static void Main(string[] args)
    {
        string yesterdaydate = DateTime.Now.AddDays(-1).ToString("yyyy-mm-dd");
        string[] SplitDate = yesterdaydate.Split('-');
        string year = SplitDate[0];
        string month = SplitDate[1];
        string day = SplitDate[2];
        string path = Path.Combine("C:\\Users\\ales\\Desktop\\test", year, month, day);

        if (Directory.Exists(path))
        {
            //do nothing
        }

        else
        {
            string fromAddress = "noreply@arm.com";
            string toAddress = "alese@arm.com";
            string subject = "error";
            string body = "failed to sync";

            krysalis_email.EmailClient email = new krysalis_email.EmailClient();
            krysalis_email.EmailClient.EmailResponse emailResponse = email.sendBasicMail(new object[] {toAddress}, fromAddress, subject, body, false, "smtp.za.arm.com",
                new string[] {"", ""}, false, null);


            if (emailResponse != null)
            {

            }

        }

    }

【问题讨论】:

  • 100% 路径错误。调试您的代码并检查path 值。此外,您可以使用 DateTime.Day/.Month/.Year 属性来访问您需要的值,而无需解析 string
  • 除了某人给出的答案之外,您可能无权访问其他用户的桌面文件夹,因此Directory.Exists() 正在返回false。如果修复日期格式MM后不起作用,请尝试以管理员身份运行程序。
  • 另外,不必将日期转换为字符串,然后提取日/月/年组件。使用 DateTime.Day、.Month 和 .Year。
  • @Fildor 我在等着看其他答案是否能先解决问题...

标签: c# if-statement directory


【解决方案1】:

问题在于您的日期格式为字符串。您正在使用mm,即分钟。使用MM 获取月份。请记住,MM 格式将为您提供带前导零的月份,例如 08 如果要使用字符串拆分,则将代码更改为

string yesterdaydate = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd");

但正如其他人指出的那样,获取值的更好方法是使用 DateTime 而不是解析字符串。这是一个例子:

DateTime yesterdaydate = DateTime.Now.AddDays(-1);
string year = yesterdaydate.Year.ToString();
string month = yesterdaydate.Month.ToString("D2");//D2 to format number to be zero-padded
string day = yesterdaydate.Day.ToString("D2");
string path = Path.Combine("C:\\Users\\ales\\Desktop\\test", year, month, day);

【讨论】:

  • 是的,我只是想添加这将使该答案更加有用。
  • @Fildor 我就是这么做的。谢谢
  • 如果文件夹名称中的数字需要补零(看起来很可能是这种情况),您需要为月/日的 ToString 调用提供格式字符串跨度>
  • 不错的收获@pinkfloydx33。谢谢
猜你喜欢
  • 1970-01-01
  • 2019-05-28
  • 2019-04-09
  • 1970-01-01
  • 2020-08-03
  • 2022-08-18
  • 2018-03-29
  • 2014-11-11
  • 2015-05-16
相关资源
最近更新 更多