分享.NET开发中经常使用到的代码片段 完全从实际项目中提取出来,也可被反反复复的重复借用...
幾年前,一篇《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 = ; ????? }}
? 調用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編譯的。在我的代碼生成可器中,它用來反射讀取程序集信息,生成代碼,而這個被讀取的程序集的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 folder
private void OnChanged(object source, FileSystemEventArgs e)
{string word = DocumentUtility.ConvertPdfToDoc(e.FullPath);
} ?
希望可以幫助到你。
轉載于:https://www.cnblogs.com/JamesLi2015/archive/2011/12/01/2269996.html
總結
以上是生活随笔為你收集整理的分享.NET开发中经常使用到的代码片段 完全从实际项目中提取出来,也可被反反复复的重复借用...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 个性签名大全英语
- 下一篇: vs中将网站aspx.cs文件打包成一个