【发布时间】:2017-12-16 17:10:54
【问题描述】:
我正在将 .NET Framework 4.5 应用程序移植到 .NET Core 2.0 并已开始在我的 Mac 上进行一些测试。当我在 Windows 上的 .NET Core 2.0 上运行此代码时,它运行良好:
TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
但它会在 Mac 上引发以下异常:
System.TimeZoneNotFoundException: The time zone ID 'Pacific Standard Time' was not found on the local computer. ---> System.IO.FileNotFoundException: Could not find file '/usr/share/zoneinfo/Pacific Standard Time'.
at Interop.ThrowExceptionForIoErrno(ErrorInfo errorInfo, String path, Boolean isDirectory, Func`2 errorRewriter)
at Microsoft.Win32.SafeHandles.SafeFileHandle.Open(String path, OpenFlags flags, Int32 mode)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options)
at System.IO.File.ReadAllBytes(String path)
at System.TimeZoneInfo.TryGetTimeZoneFromLocalMachine(String id, TimeZoneInfo& value, Exception& e)
--- End of inner exception stack trace ---
at System.TimeZoneInfo.FindSystemTimeZoneById(String id)
经过一番摸索,似乎使用时区 ID "America/Los_Angeles" 可以解决 Mac 上的问题。
我想知道我应该做些什么来保持这个平台不可知论。我是否应该尝试找到"Pacific Standard Time",然后尝试在catch 块中找到"America/Los Angeles"?这看起来很笨拙,如果另一个平台有另一个字符串呢?有没有更好的方法来查找我想要的 TimeZoneInfo?
【问题讨论】: