开发者

Confused about why a labels .Tag property, isn't doing what I think it should

开发者 https://www.devze.com 2023-03-26 10:59 出处:网络
I\'m using C# in a WinForms application. I\'m trying to set the value of a label based on the date of a file. The \"File.GetLastWriteTime\" method will return \"12/31/1600\" if it doesn\'t find th开发

I'm using C# in a WinForms application. I'm trying to set the value of a label based on the date of a file. The "File.GetLastWriteTime" method will return "12/31/1600" if it doesn't find th开发者_开发问答e file. If it doesn't, I want the label to show "Not found". When stepping through the code below, the value for the lblSqlC.Tag match's "12/31/1600". yet the "If" statement finds it false.

lblSqlC.Tag = File.GetLastWriteTime(@"c:\sql.exe").ToShortDateString();

if (lblSqlC.Tag == "12/31/1600")
{
   lblSqlC.Text = "Not Found";
}
else
{
   lblSqlC.Text = lblSqlC.Tag;
}

What am I missing? Thanks.


You need to compare strings as strings if you're using the == operator. So this block:

if (lblSqlC.Tag == "12/31/1600")
{
   lblSqlC.Text = "Not Found";
}

Should be changed to either:

if ((string)lblSqlC.Tag == "12/31/1600")
{
   lblSqlC.Text = "Not Found";
}

Or:

if (lblSqlC.Tag != null && lblSqlC.Tag.Equals("12/31/1600"))
{
   lblSqlC.Text = "Not Found";
}

Otherwise, as @dtb mentions, it simply uses the default == operator defined on object and tests that the references are equal (and they probably are not equal) as opposed to their values.


There are multiple problems with your code:

  1. The Tag Property is of type Object, so your comparison tests if the object stored in the Tag Property is the same reference as "12/31/1600" which is not the case.

  2. You're converting the DateTime value to a string, which results in a different string depending on the operating system's locale settings. So even if 1. worked, your code wouldn't work on all systems.

Use File.Exists to check if the file exists or not:

if (!File.Exists(@"c:\sql.exe"))
{
   lblSqlC.Text = "Not Found";
}
else
{
   lblSqlC.Text = File.GetLastWriteTime(@"c:\sql.exe").ToShortDateString();
}

If you really want to avoid using File.Exists, compare the value returned by File.GetLastWriteTime to a DateTime value, without converting to string:

DateTime dt = File.GetLastWriteTime(@"c:\sql.exe");

// If the file does not exist, GetLastWriteTime returns 12:00 midnight,
// January 1, 1601 A.D. (C.E.) Coordinated Universal Time (UTC), adjusted
// to local time.
if (dt == new DateTime(1601, 1, 1, 0, 0, 0, DateTimeKind.Utc))
{
   lblSqlC.Text = "Not Found";
}
else
{
   lblSqlC.Text = dt.ToShortDateString();
}
0

精彩评论

暂无评论...
验证码 换一张
取 消