Reading and Writing Text File

Text files provide a common denominator format where both people and programs can read and understand. The .NET Framework includes convenience classes that make reading and writing text files very easy. The following sequence outlines the basic steps necessary to work with text files:

  1. Open the file
  2. Read/Write to the file
  3. Close the file

It's that simple. Listing 1 shows how to write text data to a file.

Writing to a Text File

Listing 1: Writing Text Data to a File: TextFileWriter.cs

using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileWriter
{
static void Main(string[] args)
{
// create a writer and open the file
TextWriter tw = new StreamWriter("date.txt");

// write a line of text to the file
tw.WriteLine(DateTime.Now);

// close the stream
tw.Close();
}
}
}

This program creates a text file when it runs. In the directory where the executable program is located, you'll find a file named date.txt. If you view the contents of this file, you'll see the following textual representation of the date and time when the program last ran:

2/15/2002 8:54:51 PM

The first task in Listing 1 is to open the file. This happens by instantiating a StreamWriter class, which returns an object of type TextWriter. The result could have also been assigned to a StreamWriter instance. The StreamWriter was called with a single parameter, indicating the name of the file to open. If this file doesn't exist, the StreamWriter will create it. The StreamWriter also has 6 other constructor overloads that permit you to specify the file in different ways, buffer info, and text encoding. Here's the line that opens the date.txt file:

TextWriter tw = new StreamWriter("date.txt");

Using the TextWriter instance, tw, you can write text info to the file. The example writes the text for the current date and time, using the static Now property of the DateTime class. Here's the line from the code:

tw.WriteLine(DateTime.Now);

When you're done writing to the file, be sure to close it as follows:

tw.Close();

Reading From a Text File

Listing 2 shows how to read from a text file:

Listing 2: Reading Text Data from a File: TextFileReader.cs

using System;
using System.IO;

namespace csharp_station.howto
{
class TextFileReader
{
static void Main(string[] args)
{
// create reader & open file
Textreader tr = new StreamReader("date.txt");

// read a line of text
Console.WriteLine(tr.ReadLine());

// close the stream
tr.Close();
}
}
}

In Listing 2, the text file is opened in a manner similar to the method used in Listing 1, except it uses a StreamReader class constructor to create an instance of a Textreader. The StreamReader class includes additional overloads that allow you to specify the file in different ways, text format encoding, and buffer info. This program opens the date.txt file, which should be in the same directory as the executable file:

Textreader tr = new StreamReader("date.txt");

Within a Console.WriteLine statement, the program reads a line of text from the file, using the ReadLine() method of the Textreader instance. The Textreader class also includes methods that allow you to invoke the Read() method to read one or more character or use the Peek() method to see what the next character is without pulling it from the stream. Here's the code that reads an entire line from the text file:

Console.WriteLine(tr.ReadLine());

When done reading, you should close the file as follows:

tr.Close();

Summary

This article showed how to write text to a file and read it back out. For more details on additional methods, consult the .NET Frameworks reference on the StreamWriter, StreamReader, TextWriter, and Textreader classes.

0 comments  

Reading Excel files from .NET/C#

First you must declare using namespace


using Microsoft.Office.Interop.Excel;
if the Office Primary Interop Assemblies is installed in your system. If not, you can get it at http://www.microsoft.com/downloads/details.aspx?FamilyId=C41BD61E-3060-4F71-A6B4-01FEBA508E52&displaylang=en

Microsoft has changed the design of Office Primary Interop Assemblies in Office 2003. So if you want to read Excel files from a system with Office 2002 or before, you must use:

   Excel.Application excel = new Excel.Application();

Excel.Workbook theWorkbook = excel.Workbooks.Open(
FileName,,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);
You can't use null as parameters, that will cause an exception.

in Office 2003, Excel is just a namespace and everything has a Class postfix:


ApplicationClass excel=new ApplicationClass();

Workbook theWorkbook = excel.Workbooks.Open(
FileName,,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value,
Missing.Value,Missing.Value,Missing.Value,Missing.Value,Missing.Value);

After you open the workbook, you can use the following codes to get data into your memory:

ws=(Worksheet)wb.Sheets[1];
r=ws.get_Range("B3","K100");
values=(object[,])r.Value2;
the Range.Value2 return a 2-dimension array of object. The first represents rows and the second represents columns. For example, if you want to get the value in B10, which is the 8-th row and the first column is return range r. You can use

v=values[8,1].ToString();
to get the value. You will know many features in Excel COM Model are missing in the .NET imlementation.

Source : http://blog.jumbosoft.com/alvincho/PermaLink,guid,77f86a28-206f-4474-b12b-1fcc6160a286.aspx

0 comments  

Structs Tutorial

This tutorial presents the syntax and usage of structs. It also covers the important differences between classes and structs.

Tutorial

This tutorial includes two examples. The first example shows you how to declare and use structs, and the second example demonstrates the difference between structs and classes when instances are passed to methods. You are also introduced to the following topics:

  • Structs vs. Classes
  • Heap or Stack?
  • Constructors and Inheritance
  • Attributes on Structs

Example 1

This example declares a struct with three members: a property, a method, and a private field. It creates an instance of the struct and puts it to use:

// struct1.cs
using System;
struct SimpleStruct
{
private int xval;
public int X
{
get
{
return xval;
}
set
{
if (value < 100)
xval = value;
}
}
public void DisplayX()
{
Console.WriteLine("The stored value is: {0}", xval);
}
}

class TestClass
{
public static void Main()
{
SimpleStruct ss = new SimpleStruct();
ss.X = 5;
ss.DisplayX();
}
}

Output

The stored value is: 5

Structs vs. Classes

Structs may seem similar to classes, but there are important differences that you should be aware of. First of all, classes are reference types and structs are value types. By using structs, you can create objects that behave like the built-in types and enjoy their benefits as well.

Heap or Stack?

When you call the New operator on a class, it will be allocated on the heap. However, when you instantiate a struct, it gets created on the stack. This will yield performance gains. Also, you will not be dealing with references to an instance of a struct as you would with classes. You will be working directly with the struct instance. Because of this, when passing a struct to a method, it's passed by value instead of as a reference.

Example 2

This example shows that when a struct is passed to a method, a copy of the struct is passed, but when a class instance is passed, a reference is passed.

// struct2.cs
using System;

class TheClass
{
public int x;
}

struct TheStruct
{
public int x;
}

class TestClass
{
public static void structtaker(TheStruct s)
{
s.x = 5;
}
public static void classtaker(TheClass c)
{
c.x = 5;
}
public static void Main()
{
TheStruct a = new TheStruct();
TheClass b = new TheClass();
a.x = 1;
b.x = 1;
structtaker(a);
classtaker(b);
Console.WriteLine("a.x = {0}", a.x);
Console.WriteLine("b.x = {0}", b.x);
}
}

Output

a.x = 1
b.x = 5

Code Discussion

The output of the example shows that only the value of the class field was changed when the class instance was passed to the classtaker method. The struct field, however, did not change by passing its instance to the structtaker method. This is because a copy of the struct was passed to the structtaker method, while a reference to the class was passed to the classtaker method.

Constructors and Inheritance

Structs can declare constructors, but they must take parameters. It is an error to declare a default (parameterless) constructor for a struct. Struct members cannot have initializers. A default constructor is always provided to initialize the struct members to their default values.

When you create a struct object using the New operator, it gets created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the New operator. If you do not use New, the fields will remain unassigned and the object cannot be used until all the fields are initialized.

There is no inheritance for structs as there is for classes. A struct cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class object. A struct can implement interfaces, and it does that exactly as classes do. Here's a code snippet of a struct implementing an interface:

interface IImage
{
void Paint();
}

struct Picture : IImage
{
public void Paint()
{
// painting code goes here
}
private int x, y, z; // other struct members
}

Attributes on Structs

By using attributes you can customize how structs are laid out in memory. For example, you can create what's known as a union in C/C++ by using the StructLayout(LayoutKind.Explicit) and FieldOffset attributes.

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct TestUnion
{
[FieldOffset(0)]
public int i;
[FieldOffset(0)]
public double d;
[FieldOffset(0)]
public char c;
[FieldOffset(0)]
public byte b1;
}

In the preceding code segment, all of the fields of TestUnion start at the same location in memory.

The following is another example where fields start at different explicitly set locations:

using System.Runtime.InteropServices;
[StructLayout(LayoutKind.Explicit)]
struct TestExplicit
{
[FieldOffset(0)]
public long lg;
[FieldOffset(0)]
public int i1;
[FieldOffset(4)]
public int i2;
[FieldOffset(8)]
public double d;
[FieldOffset(12)]
public char c;
[FieldOffset(14)]
public byte b1;
}

The two int fields, i1 and i2, share the same memory locations as lg. This sort of control over struct layout is useful when using platform invocation.

Conclusion

Structs are simple to use and can prove to be useful at times. Just keep in mind that they're created on the stack and that you're not dealing with references to them but dealing directly with them. Whenever you have a need for a type that will be used often and is mostly just a piece of data, structs might be a good option.

0 comments  

Collection Classes Tutorial

The foreach statement is a convenient way to iterate over the elements of an array. It can also enumerate the elements of a collection, provided that the collection class has implemented the System.Collections.IEnumerator and System.Collections.IEnumerable interfaces.

Example 1

The following code sample illustrates how to write a collection class that can be used with foreach. The class is a string tokenizer, similar to the C run-time function strtok.

// tokens.cs
using System;
// The System.Collections namespace is made available:
using System.Collections;

// Declare the Tokens class:
public class Tokens : IEnumerable
{
private string[] elements;

Tokens(string source, char[] delimiters)
{
// Parse the string into tokens:
elements = source.Split(delimiters);
}

// IEnumerable Interface Implementation:
// Declaration of the GetEnumerator() method
// required by IEnumerable
public IEnumerator GetEnumerator()
{
return new TokenEnumerator(this);
}

// Inner class implements IEnumerator interface:
private class TokenEnumerator : IEnumerator
{
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t)
{
this.t = t;
}

// Declare the MoveNext method required by IEnumerator:
public bool MoveNext()
{
if (position < position =" -1;" f =" new">

Output

This
is
a
well
done
program.

Code Discussion

In the preceding example, the following code is used to Tokens by breaking "This is a well-done program." into tokens (using ' ' and '-' as separators) and enumerating those tokens with the foreach statement:

Tokens f = new Tokens("This is a well-done program.",
new char[] {' ','-'});
foreach (string item in f)
{
Console.WriteLine(item);
}

Notice that, internally, Tokens uses an array, which implements IEnumerator and IEnumerable itself. The code sample could have leveraged the array's enumeration methods as its own, but that would have defeated the purpose of this example.

In C#, it is not strictly necessary for a collection class to inherit from IEnumerable and IEnumerator in order to be compatible with foreach; as long as the class has the required GetEnumerator, MoveNext, Reset, and Current members, it will work with foreach. Omitting the interfaces has the advantage of allowing you to define the return type of Current to be more specific than object, thereby providing type-safety.

For example, starting with the sample code above, change the following lines:

public class Tokens  // no longer inherits from IEnumerable
public TokenEnumerator GetEnumerator() // doesn't return an IEnumerator
public class TokenEnumerator // no longer inherits from IEnumerator
public string Current // type-safe: returns string, not object

Now, because Current returns a string, the compiler can detect when an incompatible type is used in a foreach statement:

foreach (int item in f)  // Error: cannot convert string to int

The disadvantage of omitting IEnumerable and IEnumerator is that the collection class is no longer interoperable with the foreach statements (or equivalents) of other common language runtime-compatible languages.

You can have the best of both worlds — type-safety within C# and interoperability with other common language runtime-compatible languages — by inheriting from IEnumerable and IEnumerator and using explicit interface implementation, as demonstrated in the following example.

Example 2

This sample is equivalent in function to Example 1, but it provides additional type-safety in C# while maintaining interoperability with other languages.

// tokens2.cs
using System;
using System.Collections;

public class Tokens: IEnumerable
{
private string[] elements;

Tokens(string source, char[] delimiters)
{
elements = source.Split(delimiters);
}

// IEnumerable Interface Implementation:

public TokenEnumerator GetEnumerator() // non-IEnumerable version
{
return new TokenEnumerator(this);
}

IEnumerator IEnumerable.GetEnumerator() // IEnumerable version
{
return (IEnumerator) new TokenEnumerator(this);
}

// Inner class implements IEnumerator interface:

public class TokenEnumerator: IEnumerator
{
private int position = -1;
private Tokens t;

public TokenEnumerator(Tokens t)
{
this.t = t;
}

public bool MoveNext()
{
if (position < position =" -1;" f =" new">

0 comments  

Versioning Tutorial

This tutorial demonstrates versioning in C# through the use of the override and new keywords. Versioning maintains compatibility between base and derived classes as they evolve.

The C# language is designed such that versioning between base and derived classes in different libraries can evolve and maintain backwards compatibility. This means, for example, that the introduction of a new member in a base class with the same name as a member in a derived class is not an error. It also means that a class must explicitly state whether a method is intended to override an inherited method, or whether a method is a new method that simply hides a similarly named inherited method.

In C#, methods are by default, not virtual. To make a method virtual, the virtual modifier has to be used in the method declaration of the base class. The derived class can then override the base virtual method by using the override keyword or hide the virtual method in the base class by using the new keyword. If neither the override keyword nor the new keyword is specified, the compiler will issue a warning and the method in the derived class will hide the method in the base class. The following example shows these concepts in action.

Example

// versioning.cs
// CS0114 expected
public class MyBase
{
public virtual string Meth1()
{
return "MyBase-Meth1";
}
public virtual string Meth2()
{
return "MyBase-Meth2";
}
public virtual string Meth3()
{
return "MyBase-Meth3";
}
}

class MyDerived : MyBase
{
// Overrides the virtual method Meth1 using the override keyword:
public override string Meth1()
{
return "MyDerived-Meth1";
}
// Explicitly hide the virtual method Meth2 using the new
// keyword:
public new string Meth2()
{
return "MyDerived-Meth2";
}
// Because no keyword is specified in the following declaration
// a warning will be issued to alert the programmer that
// the method hides the inherited member MyBase.Meth3():
public string Meth3()
{
return "MyDerived-Meth3";
}

public static void Main()
{
MyDerived mD = new MyDerived();
MyBase mB = (MyBase) mD;

System.Console.WriteLine(mB.Meth1());
System.Console.WriteLine(mB.Meth2());
System.Console.WriteLine(mB.Meth3());
}
}

Output

MyDerived-Meth1
MyBase-Meth2
MyBase-Meth3

Code Discussion

Hiding a base class member from a derived class isn't an error in C#. This feature enables you to make changes in the base class without breaking other libraries that inherit this base class. For example, at some point you could have the following classes:

class Base {}
class Derived: Base
{
public void F() {}
}

At some later point, the base class could evolve to add a void method F() as follows:

class Base
{
public void F() {}
}
class Derived: Base
{
public void F() {}
}

Thus, in C#, both the base and derived classes can evolve freely and maintain binary compatibility.

0 comments