-
(以下内容来自http://www.fincher.org/tips/Languages/csharpLINQ.shtml)
The obligatory example for any language,(任何语言的必须的例子)注:你懂得,Hello World!
using System; public class HelloWorld { public static void Main(string[] args) { Console.Write("Hello World!"); } }
- Raw CSharp compiler(原生C#编译器)
You can compile c# using the command line version(你可以使用命令行工具来编译C#程序)
C:>csc HelloWorld.cs
HelloWorld
You can get Nant, a build tool like the old 'make', from http://sourceforge.net/projects/nant.(你可以下载Nant从http://sourceforge.net/projects/nant,一个像老的make的编译工具)
- Reading Stuff(读取相关)
- Read an entire file into a string(将整个文件读取到一个字符串中)
using System; namespace PlayingAround { class ReadAll { public static void Main(string[] args) { string contents = System.IO.File.ReadAllText(@"C:\t1"); Console.Out.WriteLine("contents = " + contents); } } }
-
Read a file with a single call to sReader.ReadToEnd() using streams(单独调用流文件的ReadToEnd()函数来读取文件)
public static string getFileAsString(string fileName) { StreamReader sReader = null; string contents = null; try { FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read); sReader = new StreamReader(fileStream); contents = sReader.ReadToEnd(); } finally { if(sReader != null) { sReader.Close(); } } return contents; }
- Read all the lines from a file into an array(从文件中读取所有行到一个数组中)
using System; namespace PlayingAround { class ReadAll { public static void Main(string[] args) { string[] lines = System.IO.File.ReadAllLines(@"C:\t1"); Console.Out.WriteLine("contents = " + lines.Length); Console.In.ReadLine(); } } }
- Read a file line by line with no error checking(没有错误检测的一行一行读取文件)
Useful if the file may be really large.(如果一个文件真的很大的话,是很有用的)
StreamReader sr = new StreamReader("fileName.txt"); string line; while((line= sr.ReadLine()) != null) { Console.WriteLine("xml template:"+line); } if (sr != null)sr.Close(); //should be in a "finally" or "using" block
- Read an entire file into a string(将整个文件读取到一个字符串中)
- Writing Stuff(写入相关)
- Easy writing all text to a file(简单的将所有文本写入到一个文件)
WriteAllText will create the file if it doesn't exist, otherwise overwrites it. It will also close the file.(WriteAllText函数将会创建文件,如果文件不存在的话;否则会覆盖已经存在的文件。它也会关闭文件)
using System; namespace PlayingAround { class ReadAll { public static void Main(string[] args) { string myText = "Line1" + Environment.NewLine + "Line2" + Environment.NewLine; System.IO.File.WriteAllText(@"C:\t2", myText); } } }
- Write a line to a file using streams(使用文件流将一行写入文件)
using System; using System.IO; public class WriteFileStuff { public static void Main() { FileStream fs = new FileStream("c:\\tmp\\WriteFileStuff.txt", FileMode.OpenOrCreate, FileAccess.Write); StreamWriter sw = new StreamWriter(fs); try { sw.WriteLine("Howdy World."); } finally { if(sw != null) { sw.Close(); } } } }
- Access files with "using"(通过using关键字来写入文件)
"using" does an implicit call to Dispose() when the using block is complete. With files this will close the file. The following code shows that using does indeed close the file, otherwise 5000 open files would cause problems.(当using块完成之后,using会隐性的调用Dispose函数,这样会关闭这个文件。下面的代码显示了,using确实会关闭文件,否则5000次打开文件会导致问题发生的。)
using System; using System.IO; class Test { private static void Main() { for (int i = 0; i < 5000; i++) { using (TextWriter w = File.CreateText("C:\\tmp\\test\\log" + i + ".txt")) { string msg = DateTime.Now + ", " + i; w.WriteLine(msg); Console.Out.WriteLine(msg); } } Console.In.ReadLine(); } }
- "using" as "typedef" (a la "C")(using像typedef)
"C" allows you to alias one type as another with typedef. In C# you can do this with "using" (can we create another overload for "using" just to make it more confusing?) Everywhere the type "RowCollection" is used, C# will understand it to be of type "List<Node>"(在C中,你可以使用typedef来为一个类型定义一个别名。在C#中,你可以使用using来完成。每个当RowCollection被用到的地方,C#都会将它理解成List<Node>类型的。)
using RowCollection = List<Node>;
-
Write a very simple XML fragment the hard way.(用硬性方法来写一个很简单的XML段)
static void writeTree(XmlNode xmlElement, int level) { String levelDepth = ""; for(int i=0;i<level;i++) { levelDepth += " "; } Console.Write("\n{0}<{1}",levelDepth,xmlElement.Name); XmlAttributeCollection xmlAttributeCollection = xmlElement.Attributes; foreach(XmlAttribute x in xmlAttributeCollection) { Console.Write(" {0}='{1}'",x.Name,x.Value); } Console.Write(">"); XmlNodeList xmlNodeList = xmlElement.ChildNodes; ++level; foreach(XmlNode x in xmlNodeList) { if(x.NodeType == XmlNodeType.Element) { writeTree((XmlNode)x, level); } else if(x.NodeType == XmlNodeType.Text) { Console.Write("\n{0} {1}",levelDepth,(x.Value).Trim()); } } Console.Write("\n{0}</{1}>",levelDepth,xmlElement.Name); }
- Write a very simple XML fragment the easier way(写入一个简单的XML段的最简单的方法)
StringWriter stringWriter = new StringWriter(); XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter); xmlTextWriter.Formatting = Formatting.Indented; xmlDocument.WriteTo(xmlTextWriter); //xmlDocument can be replaced with an XmlNode xmlTextWriter.Flush(); Console.Write(stringWriter.ToString());
- To write any object or some collections to xml(写入任何对象或集合到xml中)
Object must have a default constructor.(对象必须有一个默认的构造函数)
public static string SerializeToXmlString(object objectToSerialize) { MemoryStream memoryStream = new MemoryStream(); System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(objectToSerialize.GetType()); xmlSerializer.Serialize(memoryStream, objectToSerialize); ASCIIEncoding ascii = new ASCIIEncoding(); return ascii.GetString(memoryStream.ToArray()); }
- And this should turn the xml back into an object(下面的程序将会将xml重新转换成对象)
public static object DeSerializeFromXmlString(System.Type typeToDeserialize, string xmlString) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(xmlString); MemoryStream memoryStream = new MemoryStream(bytes); System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeToDeserialize); return xmlSerializer.Deserialize(memoryStream); } Example [Test] public void GetBigList() { var textRepository = ObjectFactory.GetInstance<ITextRepository>(); List<BrandAndCode> brandAndCodeList = textRepository.GetList(...); string xml = SerializeToXmlString(brandAndCodeList); Console.Out.WriteLine("xml = {0}", xml); var brandAndCodeList2 = DeSerializeFromXmlString(typeof (BrandAndCode[]), xml); }
-
Write formated output:(格式化输出)
int k = 16; Console.WriteLine(" '{0,-8}'",k); // produces: '16 ' Console.WriteLine(" '{0,8}'",k); // produces: ' 16' Console.WriteLine(" '{0,8}'","Test"); // produces: ' Test' Console.WriteLine(" '{0,-8}'","Test");// produces: 'Test ' Console.WriteLine(" '{0:X}'",k); //(in HEX) produces: '10' Console.WriteLine(" '{0:X10}'",k); //(in HEX) produces:'0000000010' Console.WriteLine( 1234567.ToString("#,##0")); // writes with commas: 1,234,567
- Formatting decimals in strings using String.Format()(使用String.Format()函数来格式化十进制字符串)
More info at www.codeproject.com
s.Append(String.Format("Completion Ratio: {0:##.#}%",100.0*completes/count));
s.Append(myDouble.ToString("###.###")
String.Format("{0,8:F3}",this.OnTrack)
- Format DateTime objects(格式化DateTime对象)
DateTime.Now.ToString("yyyyMMdd-HHmm"); // will produce '20060414-1529'
【更多阅读】
- Easy writing all text to a file(简单的将所有文本写入到一个文件)
- [原]PjConvertImageFormat:用FreeImage.NET写的一个35种图像格式转换程序
- [原]Cls_Ini.cls:VB写的操作ini配置文件的类
- [原]PjConvertImageFormat:用FreeImage.NET写的一个35种图像格式转换程序
- [原]GetAlpha:C#实现获取网页验证码图片,并识别出其中的字母
- [原]IniFile.cs:C#来操作ini配置文件
- [译]用C#检测你的打印机是否连接
- [原]Hotkey.cs:为应用程序添加热键
- [原]GetAlpha:C#实现获取网页验证码图片,并识别出其中的字母
- [原]DownloadWebImages:下载某页面上的所有图片
- [原]QQHelper:QQ大家来找茬 辅助工具 外挂