在 .NET 中如果引用了 System 命名空间那么我们就可以直接使用 Environment.TickCount 获得计算机启动后的毫秒数,但是如果直接把这个毫秒数输出给用户,用户很难直观的计算出到底启动了多少时间,所以我们一般都是格式化成一个可以直观看出结果的字符串以后再输出给用户,当然如果你有更好的方法欢迎给我留言。代码片段如下:
Int32 tickSecond = Environment.TickCount / 60000;
Int32 tickDay = tickSecond / 60 / 24;
Int32 tickHour = (tickSecond / 60) % 24;
Int32 tickMinute = tickSecond % 60;
String runTime = String.Format("{0} 天 {1} 小时 {2} 分", tickDay, tickHour, tickMinute);
另外提供一个小技巧就是 ASP.NET 2.0 中数据库配置文件可以使用 |DataDirectory| 来表示 App_Data 目录。
分享一个格式化文件大小的 C# 方法:
public static String FormatFileSize(Int64 fileSize)
{
if (fileSize < 0)
{
throw new ArgumentOutOfRangeException("fileSize");
}
else if (fileSize >= 1024 * 1024 * 1024)
{
return string.Format("{0:########0.00} GB", ((Double)fileSize) / (1024 * 1024 * 1024));
}
else if (fileSize >= 1024 * 1024)
{
return string.Format("{0:####0.00} MB", ((Double)fileSize) / (1024 * 1024));
}
else if (fileSize >= 1024)
{
return string.Format("{0:####0.00} KB", ((Double)fileSize) / 1024);
}
else
{
return string.Format("{0} bytes", fileSize);
}
}