最有用的.NET工具类开发人员倾向于重塑而不是重用
我最近从去年阅读了Phil Haack的post( 最有用的.NET实用程序类开发人员倾向于重新创造,而不是重用 ),并认为我会看看是否有人添加到列表中。
人们倾向于使用以下丑陋而必然失败的事物:
string path = basePath + "\\" + fileName; 更好更安全的方式:
 string path = Path.Combine(basePath, fileName); 
另外我也见过编写自定义方法的人读取文件中的所有字节。 这个很方便:
 byte[] fileData = File.ReadAllBytes(path); // use path from Path.Combine 
 正如TheXenocide指出的那样, File.ReadAllText()和File.ReadAllLines() 
 String.IsNullOrEmpty() 
 Path.GetFileNameWithoutExtension(string path) 
返回不带扩展名的指定pathstring的文件名。
 Path.GetTempFileName() 
在磁盘上创build一个唯一命名的零字节临时文件,并返回该文件的完整path。
  System.Diagnostics.Stopwatch类。 
的String.Format。
我见过的次数
 return "£" & iSomeValue 
而不是
 return String.Format ("{0:c}", iSomeValue) 
或附加百分号的人 – 这样的事情。
Enum.Parse()
试图找出我的文档在用户的计算机上的位置。 只需使用以下内容:
 string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); 
我需要在Windows应用程序中最近下载一些文件。 我在WebClient对象上find了DownloadFile方法:
  WebClient wc = new WebClient(); wc.DownloadFile(sourceURLAddress, destFileName); 
String.Join()(然而,几乎每个人都知道关于string.Split,似乎使用它每一个机会,他们得到…)
硬编码/到目录操作string与使用:
 IO.Path.DirectorySeparatorChar 
StringBuilder类,特别是方法AppendFormat 。
PS:如果您正在寻找string操作性能测量: StringBuilder与string/快速string操作与.NET 2.0
 Environment.NewLine 
使用Guid生成文件名,而不是使用:
 Path.GetRandomFileName() 
很多新的Linqfunction似乎都是未知的:
 Any<T>() & All<T>() 
 if( myCollection.Any( x => x.IsSomething ) ) //... bool allValid = myCollection.All( x => x.IsValid ); 
 ToList<T>(), ToArray<T>(), ToDictionary<T>() 
 var newDict = myCollection.ToDictionary( x => x.Name, x => x.Value ); 
 First<T>(), FirstOrDefault<T>() 
 return dbAccessor.GetFromTable( id ). FirstOrDefault(); 
 Where<T>() 
 //instead of foreach( Type item in myCollection ) if( item.IsValid ) //do stuff //you can also do foreach( var item in myCollection.Where( x => x.IsValid ) ) //do stuff //note only a simple sample - the logic could be a lot more complex 
所有非常有用的小函数都可以在Linq语法之外使用。
- 使用DebuggerDisplay属性而不是ToString()来简化debugging。
- Enumerable.Range
- 来自FSharp.Core的元组 !
System.Text.RegularExpressions.Regex
请参阅隐藏的.NET基类库类
  input.StartsWith("stuff")而不是Regex.IsMatch(input, @"^stuff") 
对于所有它隐藏在Microsoft.VisualBasic命名空间下, TextFieldParser实际上是一个非常好的csv分析器。 我看到很多人要么自己推出(糟糕的),要么使用Code Plex上的Fast CSV库,就算不知道这个已经被烧入框架了。
文件的东西。
 using System.IO; File.Exists(FileNamePath) Directory.Exists(strDirPath) File.Move(currentLocation, newLocation); File.Delete(fileToDelete); Directory.CreateDirectory(directory) System.IO.FileStream file = System.IO.File.Create(fullFilePath); 
  System.IO.File.ReadAllText与使用StreamReader为小文件编写逻辑。 
  System.IO.File.WriteAllText与使用StreamWriter编写小文件的逻辑。 
很多人似乎都喜欢手动通过XML文件来find一些东西,而不是使用XPathNaviagator。
大多数人忘记Directory.CreateDirectory()如果文件夹已经存在,会优雅地退化,并用一个无意义的if(!Directory.Exists(….))调用来包装它。
myString.Equals(anotherString)
以及包括特定文化的选项。
我敢打赌,至less有50%的开发者写这样的东西:if(s ==“id”){…}
Path.Append总是被我忘记的东西遗忘。