Working with InputOutput Streams


Working with Input/Output Streams

The System.IO namespace provides classes for reading and writing data into and from streams, including files, network streams, and so on. The Stream class provides an abstract representation of sequence of bytes. Typically you would work with a reader/writer pair of classes, which provide methods to read and write primitive typed and/or string to/from the stream. For example, the BinaryReader/BinaryWriter and StreamReader/StreamWriter classes provide reading/writing binary data and text, respectively. Additionally, StringReader/StringWriter classes provide reading/writing from a string, typically useful for manipulating in memory data. Apart from that, the System.IO namespace provides Directory, DirectoryInfo, File, FileInfo, and FileSystemInfo classes to work with operating system directories and files.

Reading Files

As the first example in the I/O section (Listing 4.4), you'll read customer information from a comma-separated value (CSV) file. Here is what the data looks like:

 
 ABC Customer,Street, City, State, 12345,ABC-1045-678 DEF Customer,Street, City, State, 12345,DEF-1045-678 XYZ Customer,Street, City, State, 12345,XYZ-1045-678 IJK Customer,Street, City, State, 12345,IJK-1045-678 using System; using System.IO; class ReadingFiles {    public static void Main()    {       String file_name = "Customers.csv";       StreamReader sr = new StreamReader(file_name);       String line;       while ((line = sr.ReadLine())!=null)       {          String[] tokens = line.Split(',');          Customer c = new Customer();          c.CustomerName = tokens[0];          c.Street = tokens[1];          c.City = tokens[2];          c.State = tokens[3];          c.ZipCode = tokens[4];          c.AccountNo = tokens[5];          Console.WriteLine(c);       }       sr.Close();    } } class Customer {    public String CustomerName;    public String Street;    public String City;    public String State;    public String ZipCode;    public String AccountNo;    public Customer()    {    }    public override String ToString()    {       return CustomerName+"\n"             +Street+","+City+","+State+" "+ZipCode+"\n"             +"\tAcc #:"+AccountNo+"\n\n";    } } 

Compiling and running the program should yield the following output:

 
 ABC Customer Street, City, State  12345         Acc #:ABC-1045-678 DEF Customer Street, City, State  12345         Acc #:DEF-1045-678 ... 

Creating and Writing Files

In the previous example you used StreamReader to read information from a file stream. In Listing 4.5, you will use the StreamWriter to write customer information into an outgoing CSV file.

Listing 4.5 Reading Files
 using System; using System.IO; class CreateFile {    public static void Main()    {       String file_name = "CustomersOut.csv";       StreamWriter sw = new StreamWriter(file_name);       Customer c = new Customer();       c.Name = "ABC Chemicals";       c.Street = "123 Some Street";       c.City = "Some City";       c.State = "NJ";       c.ZipCode = "08520";       c.AccountNo = "ABC-124567";       sw.WriteLine(c.ToCSV());       sw.Close();    } } class Customer {    public String Name;    public String Street;    public String City;    public String State;    public String ZipCode;    public String AccountNo;    public Customer()    {    }    public String ToCSV()    {       return Name+","+Street+","+City+","+State+","+ZipCode+","+AccountNo;    } } 

After running the preceding example, if you examine the content of the CustomersOut.csv file, you should see the following content:

 
 ABC Chemicals,123 Some Street,Some City,NJ,08520,ABC-124567 

Listing Files

Next, take a look at an example that examines the contents of a particular file directory. For instance, Listing 4.6 mimics the operating system's Dir command by listing the C# Source files in the current directory.

Listing 4.6 Reading Files
 using System; using System.IO; class Dir {    public static void Main()    {       FileInfo[] files = new DirectoryInfo(                       Environment.CurrentDirectory).GetFiles("*.cs");       foreach (FileInfo file in files)       {          Console.WriteLine("{0}\t{1}\t\t{2}",             file.CreationTime,file.Length,file.Name);       }    } } 

Using Isolated Storage

Isolated storage is a new concept introduced by the .NET Framework and provides .NET applications the concept of isolated stores. With isolated storage, applications can store and retrieve data to and from an isolated area in the user 's file system. It is called isolated because it is stored in a particular area of the file system; the application doesn't really know where exactly it is stored, but just has a handle to it. This concept is particularly useful in applications that are downloaded from the network, also known as partially trusted applications. You will learn more about this topic in Chapter 14, "Security." The isolated storage implementation is provided by the classes and interfaces in the System.IO.IsolatedStorage namespace. Key classes in the namespace are IsolatedStorage and IsolatedStorageFile.

Take a look at how an application can get access to a file stored in isolated storage. In Listing 4.7, you are storing a set of preferences for the current user of the application in a file called MyApp.preferences. You can also look at how you read the information back. Note that the difference between reading and writing information to and from the isolated storage lies in getting the handle to the file; the rest of the logic stays the same.

Listing 4.7 Using Isolated Storage
 using System; using System.IO; using System.IO.IsolatedStorage; class UseIsolatedStorage {    public static void Main()    {       IsolatedStorageFileStream file =        new IsolatedStorageFileStream("MyApp.preferences", FileMode.Create);       StreamWriter sw = new StreamWriter(file);       sw.WriteLine("UserType=Business Analyst");       sw.WriteLine("UserModer=Advanced");       sw.Close();       file.Close();       file = new IsolatedStorageFileStream(          "MyApp.preferences", FileMode.Open);       StreamReader reader = new StreamReader(file);       String prefs = reader.ReadToEnd();       Console.WriteLine(prefs);       file.Close();      } } 

Listing 4.8 shows the list of current files in the user's isolated storage:

Listing 4.8 Reading Files
 using System.Net; using System; using System.Collections; using System.IO; using System.IO.IsolatedStorage; using System.Security.Policy; class QueryIsolatedStorage {    public static void Main()    {       IsolatedStorageFile isfs =                  IsolatedStorageFile.GetStore(IsolatedStorageScope.User                   IsolatedStorageScope.Assembly, null,null);       IEnumerator e = IsolatedStorageFile.GetEnumerator(IsolatedStorageScope.User);       while (e.MoveNext())       {           IsolatedStorageFile isf = (IsolatedStorageFile) e.Current;          Url assemblyUrl = (Url) isf.AssemblyIdentity;          Console.WriteLine("Assembly:"+assemblyUrl.Value);          string[] files = isf.GetFileNames("*");          foreach (string file in files) {             Console.WriteLine("\t"+file);          }       }    } } 

Running the Query application (after running the UseIsolatedStorage application) should yield the following results:

 
 Assembly:file://E:/hks/DotNet/Chapter 4/QueryIsolatedStorage.exe Assembly:file://E:/hks/DotNet/Chapter 4/UseIsolatedStorage.exe         MyApp.preferences 


Microsoft.Net Kick Start
Microsoft .NET Kick Start
ISBN: 0672325748
EAN: 2147483647
Year: 2003
Pages: 195
Authors: Hitesh Seth

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net