我對創建.NET項目時可能在Program.cs中使用的任何常用例程/過程/方法感興趣。例如,我通常在我的桌面應用程序中使用以下代碼,以允許輕鬆升級,單實例執行以及未捕獲的系統應用程序錯誤的友好和簡單的報告。你在Program.cs中爲C#添加了哪些常用的例程?
using System;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
namespace NameoftheAssembly
{
internal static class Program
{
/// <summary>
/// The main entry point for the application. Modified to check for another running instance on the same computer and to catch and report any errors not explicitly checked for.
/// </summary>
[STAThread]
private static void Main()
{
//for upgrading and installing newer versions
string[] arguments = Environment.GetCommandLineArgs();
if (arguments.GetUpperBound(0) > 0)
{
foreach (string argument in arguments)
{
if (argument.Split('=')[0].ToLower().Equals("/u"))
{
string guid = argument.Split('=')[1];
string path = Environment.GetFolderPath(Environment.SpecialFolder.System);
var si = new ProcessStartInfo(path + "\\msiexec.exe", "/x" + guid);
Process.Start(si);
Application.Exit();
}
}
//end of upgrade
}
else
{
bool onlyInstance = false;
var mutex = new Mutex(true, Application.ProductName, out onlyInstance);
if (!onlyInstance)
{
MessageBox.Show("Another copy of this running");
return;
}
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
Application.ThreadException += ApplicationThreadException;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
var ex = (Exception) e.ExceptionObject;
MessageBox.Show("Whoops! Please contact the developers with the following"
+ " information:\n\n" + ex.Message + ex.StackTrace,
" Fatal Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
catch (Exception)
{
//do nothing - Another Exception! Wow not a good thing.
}
finally
{
Application.Exit();
}
}
public static void ApplicationThreadException(object sender, ThreadExceptionEventArgs e)
{
try
{
MessageBox.Show("Whoops! Please contact the developers with the following"
+ " information:\n\n" + e.Exception.Message + e.Exception.StackTrace,
" Error", MessageBoxButtons.OK, MessageBoxIcon.Stop);
}
catch (Exception)
{
//do nothing - Another Exception! Wow not a good thing.
}
}
}
}
我發現這些程序是非常有幫助的。你發現什麼方法對Program.cs有幫助?
我覺得這很可怕,你只是放棄了任何額外的例外。 – 2009-11-03 14:48:45
我不認爲他會在場上拋出額外的例外。他忽略的唯一例外是當他實際向用戶顯示錯誤消息時引發的異常,即對MessageBox.Show()的調用。 – 2009-11-03 15:09:17