Eddie Jackson



>

[pic]

Code Samples:

1. The obligatory example for any language,

using System;

using System.Threading;

public class HelloWorld

{

public static void Main(string[] args)

{

Console.Write("Hello World!"); //write to screen

Thread.Sleep(5000); //wait 5 seconds

//Console.In.ReadLine(); //will wait for {ENTER} key if uncommented

}

}

2. 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 .

3. Reading file into string

1. Read an entire file into a string

using System;

using System.IO;

using System.Threading;

namespace PlayingAround

{

class ReadAll

{

public static void Main(string[] args)

{

string contents = File.ReadAllText(@"C:\test.txt"); //creates {contents} variable

Console.Out.WriteLine("contents = " + contents); //outputs {contents} to screen

Thread.Sleep(5000); //wait 5 seconds

//Console.In.ReadLine(); //will wait for {ENTER} key if uncommented

}

}

}

2. 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;

}

3. 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();

}

}

}

4. 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

4. Writing To A Text File

1. 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);

}

}

}

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

}

}

}

3. Access files with "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 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();

}

}

4. Write a very simple XML fragment the hard way.

static void writeTree(XmlNode xmlElement, int level) {

String levelDepth = "";

for(int i=0;i Jet = {0}", plane > jet);

Console.ReadLine();

}

}

8. Example of using Properties instead of accessor methods. Note the special use of the "value" variable in "set".

public class Plane {

protected double mySpeed = 300.0D;

public double TopSpeed {

get {return mySpeed;}

set { mySpeed = value; }

}

}

class Jet : Plane {

public Jet() { TopSpeed = 900.0D; }

}

class Airport {

[STAThread]

static void Main(string[] args) {

Plane plane = new Plane();

Console.WriteLine("plane's top speed: {0}",Speed);

Jet jet = new Jet();

Console.WriteLine("jet's top speed: {0}",Speed);

Console.ReadLine();

}

}

9. Write the current time

DateTime dt = DateTime.Now;

Console.WriteLine("Current Time is {0} ",dt.ToString());

To specify a format: dt.ToString("yyyy/MM/dd")

The cultural-independent universal format: dt.ToString("u")

which prints "yyyy'-'MM'-'dd HH':'mm':'ss'Z'"

10. Write a few lines to a file

using System.IO;

...

try {

StreamWriter streamWriter = new StreamWriter("tmp.txt");

streamWriter.WriteLine("This is the first line.");

streamWriter.WriteLine("This is the second line.");

} finally {

if(streamWriter != null) {

streamWriter.Close();

}

}

11. Download a web page and print to console all the urls on the command line

using System;

using ;

using System.Text;

using System.IO;

namespace Test {

class GetWebPage {

public static void Main(string[] args) {

for(int i=0;ilt;args.Length;i++) {

HttpWebRequest httpWebRequest =

(HttpWebRequest)WebRequest.Create(args[i]);

HttpWebResponse httpWebResponse =

(HttpWebResponse)httpWebRequest.GetResponse();

Stream stream = httpWebResponse.GetResponseStream();

StreamReader streamReader =

new StreamReader(stream, Encoding.ASCII);

Console.WriteLine(streamReader.ReadToEnd());

}

Console.Read();

}

}

}

Or you can use a static method to download a web page into a string:

public static string GetWebPageAsString(string url) {

HttpWebRequest httpWebRequest =(HttpWebRequest)WebRequest.Create(url);

HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

Stream stream = httpWebResponse.GetResponseStream();

StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);

return streamReader.ReadToEnd();

}

12. Download response with errors

How to get the content of the page even with errors like 500 or 404 is shown below:

public static string GetWebPageAsString(string url)

{

HttpWebRequest httpWebRequest = (HttpWebRequest) WebRequest.Create(url);

HttpWebResponse httpWebResponse = null;

string xml = "";

try

{

httpWebResponse = (HttpWebResponse) httpWebRequest.GetResponse();

}

catch (WebException exception)

{

if (exception.Status == WebExceptionStatus.ProtocolError)

{ //get the response object from the WebException

httpWebResponse = exception.Response as HttpWebResponse;

if (httpWebResponse == null){ return "";}

}

}

Stream stream = httpWebResponse.GetResponseStream();

StreamReader streamReader = new StreamReader(stream, Encoding.ASCII);

xml = streamReader.ReadToEnd();

//streamReader.Close();

if (httpWebResponse.StatusCode != .HttpStatusCode.OK)

{

throw new Exception(xml);

}

return xml;

}

13. Use System.Web.HttpUtility.HtmlEncode() to encode strings for display in the browser. Converts " ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download