Learning CSHARP by Example

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.

 
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);
        }
    }
}

Learning CSHARP by Example

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);
        }
    }
}

Learning CSHARP by Example

Read a file with a single call to sReader.ReadToEnd() using streams

 
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;
}

Learning CSHARP by Example

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();
        }
    }
}

Learning CSHARP by Example

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

Learning CSHARP by Example

The obligatory example for any language,

 
using System;
public class HelloWorld
{
    public static void Main(string[] args) {
            Console.Write("Hello World!");
    }
}

Raw CSharp compiler

You can compile c# using the command line version
C:>csc HelloWorld.cs

and then run the new program by entering

HelloWorld

You can get Nant, a build tool like the old 'make', from http://sourceforge.net/projects/nant.

Reference By http://www.fincher.org/tips/Languages/csharp.shtml