幾年前,一篇《ASP.NET開發人員經常使用的三十三種代碼》非常流行,它總結了一些經常在ASP.NET開發中使用到的代碼,直接可以拿來使用。今天重讀這篇文章,有感而發,善於總結也是進步,於是我也從我的項目中總結一些常用的程式碼片段,分享給各位園友。
寫文字檔
TextWriter tw = new StreamWriter("date.txt");tw.WriteLine(DateTime.Now);tw.Close();
讀文字檔
寫法一
Textreader tr = new StreamReader("date.txt");Console.WriteLine(tr.ReadLine());tr.Close();寫法二
StreamReader reader = new StreamReader("date.txt");Console.WriteLine(reader.ReadLine()); reader.Close();
其實,上面的寫文字檔和讀文字檔,都有一個bug,當程式中有代碼改變目前的目錄時,date.txt的目錄就是這個被改變的目錄,而不是我們期待的當前應用程式所有的目錄。所以,推薦的寫法是這樣的
string file = "Cnblogs.txt";string cnblogs = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, file);if (File.Exists(cnblogs)){ using (StreamReader reader = File.OpenText(cnblogs)) { rtfCnblogs.Text = reader.ReadToEnd(); }}
加入了完整的檔案名稱路徑,這樣才是正確的讀寫檔案的方法。如果是ASP.NET應用程式,可以用Server.MapPath代替,
或是HttpContext.Current.Request.PhysicalApplicationPath。
跨線程訪問控制項
delegate void dSetText(string text);private void SetText(string text) {
if (InvokeRequired)
{
dSetText d = new dSetText(SetText);
this.Invoke(d);
}
else {
this.textBox1.Text = text;
} }
調用Code Smith模板
CodeTemplateCompiler compiler = new CodeTemplateCompiler(@"c:\test.cst");compiler.Compile(); if (compiler.Errors.Count == 0){CodeTemplate t = compiler.CreateInstance();this.txtSql.Text = t.RenderToString();} compiler.Cleanup();compiler = null;
如果是x64的系統,請設定Target為x86(need to set the program to compile as X86)。
設定程式集運行時版本
當舊的程式是以.NET 2.0編譯的,又無法升級到.NET 4.0,而有部分組件是以.NET編譯的,在運行時,會拋出混合程式集的異常,需要修改設定檔,請參考這個片段
<?xml version ="1.0"?><configuration><startup useLegacyV2RuntimeActivationPolicy="true"><requiredRuntime safemode="true" imageVersion="v4.0.30319" version="v4.0.30319"/></startup></configuration>
這個需求源於,Code Smith 5.0是以.NET 2.0編譯的。在My Code產生可器中,它用來反射讀取程式集資訊,產生代碼,而這個被讀取的程式集的Target是.NET 4.0,這時,你需要這個技巧來解決運行時的問題。
另一個情境是ILMerge,用於合并.NET程式集的工具,只有.NET 2.0的版本,要可以合并.NET 4.0的程式集,也需要運用這個技巧(ILMerge config file for executing within the CLR v4.0 runtime)。
枚舉類型的反射調用
在有些情境,我們需要把反射的參數值傳到對象的方法中,而參數值是enum類型,這實現起來並不簡單。
請參考codeproject中這的篇文章《Setting Enum's Through Reflection 》,它的經典代碼是這樣的
int enumValue1 = (int)enumItem1.GetValue(enumType);int enumValue2 = (int)enumItem2.GetValue(enumType);int currentValue = (int)flagsInfo.GetValue(remoteObject, null);int newValue = currentValue | enumValue1 | enumValue2;
舉例說明,我需要反射產生ReportViewer控制項的對象執行個體,並且要傳一個Mode值給它(Server,LocalReport)以表示是本地報表,還是取伺服器報表。這種情況下,非得用反射的方式傳入值。
在我的.NET通用平台中,也應用到這項技術,以反射方式建立CrystalReportViewer報表控制項,再傳入參數值。這種方式稍微複雜一些,但是對比它帶來的靈活性,是非常值得的。
目錄選擇功能
FolderBrowserDialog dlg = new FolderBrowserDialog();if (!string.IsNullOrEmpty(txtPath.Text)) dlg.SelectedPath = txtPath.Text;if (dlg.ShowDialog() == DialogResult.OK){ txtPath.Text = dlg.SelectedPath;}
檔案選擇功能
OpenFileDialog dlg = new OpenFileDialog();dlg.Filter = "All File(*.*)|*.*";if (dlg.ShowDialog() == DialogResult.OK){ txtPath.Text = dlg.FileName;}
Filter是經常容易忘記的選項,再舉一個例子
dlg.Filter = "Xml file (*.xml)|*.xml|All Files|*.*";
讀取嵌入到程式集中的資源檔
Assembly assm = Assembly.GetAssembly(typeof(DatabaseCleanup));string file = "DatabaseCleanup.txt";Stream input = assm.GetManifestResourceStream("DataLoader.Resource" + "." + file); StreamReader reader=new StreamReader(input);string sql=reader.ReadToEnd();reader.Close();
只要可能,對唯讀不需要修改的配置選項資源(SQL語句,文字檔),儘可能的使用Embedded Resource方式。
微軟企業庫的調用方式
經過一層簡單的封裝,以下面的這種方式來調用企業庫以訪問資料庫
EnterpriseLibraryShared.ConnectonString =ConnectionString;Microsoft.Practices.EnterpriseLibrary.Data.Database m_commonDb = DatabaseFactory.CreateDatabase();DbCommand cmd = m_commonDb.GetSqlStringCommand(sql);int rowAffected = m_commonDb.ExecuteNonQuery(cmd);
我把企業庫的連接字串放到一個static class中,這樣可以簡化調用方式,不必要一定要加App/Web.config檔案。
監控檔案或目錄的變化
這個功能比較常用,在Data Loader也有一個PDF Watcher的程式,以監控指定的目錄是否有新加入的PDF檔案(可能來自遠程傳輸,或是從網頁中下載回來),然後對它進轉換,匯入到文檔伺服器中。
public void StartMonitor(string path){ FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; watcher.NotifyFilter = NotifyFilters.FileName; // Only watch pdf files. watcher.Filter = "*.pdf"; watcher.Created += new FileSystemEventHandler(OnChanged); watcher.EnableRaisingEvents = true;}// Event handler for when a file is created in the watched folderprivate void OnChanged(object source, FileSystemEventArgs e){ string word = DocumentUtility.ConvertPdfToDoc(e.FullPath);}
希望可以協助到你。