FileStream with FileMode.Create and FileMode.Open

image_pdfimage_print
   

using System;
using System.IO;
using System.Text;

class MainClass {
    static void Main() {
        using (FileStream fs = new FileStream("test.txt", FileMode.Create)) {
            using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) {
                w.WriteLine(124.23M);
                w.WriteLine("Test string");
                w.WriteLine('!');
            }
        }
        Console.WriteLine("Press Enter to read the information.");
        Console.ReadLine();
        // Open the file in read-only mode.
        using (FileStream fs = new FileStream("test.txt", FileMode.Open)) {
            using (StreamReader r = new StreamReader(fs, Encoding.UTF8)) {
                // Read the data and convert it to the appropriate data type.
                Console.WriteLine(Decimal.Parse(r.ReadLine()));
                Console.WriteLine(r.ReadLine());
                Console.WriteLine(Char.Parse(r.ReadLine()));
            }
        }
    }
}
           
          


Set File IO Permission to c:

image_pdfimage_print
   


using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Permissions;


class Program {
    static void Main(string[] args) {
        MyClass.Method();
    }
}

[FileIOPermission(SecurityAction.Assert, Read = "C:/")]
class MyClass {
    public static void Method() {
        // implementation goes here
    }
}

           
          


Create a file stream with new FileStream(“test.bin”, FileMode.Create)

image_pdfimage_print
   
 

using System;
using System.IO;

class MainClass {
    static void Main() {
        using (FileStream fs = new FileStream("test.bin", FileMode.Create)) {
            using (BinaryWriter w = new BinaryWriter(fs)) {
                w.Write(124.23M);
                w.Write("Tstring");
                w.Write("Tstring 2");
                w.Write('!');
            }
        }
        Console.WriteLine("Press Enter to read the information.");
        Console.ReadLine();

        using (FileStream fs = new FileStream("test.bin", FileMode.Open)) {
            using (StreamReader sr = new StreamReader(fs)) {
                Console.WriteLine(sr.ReadToEnd());
                Console.WriteLine();

                fs.Position = 0;
                using (BinaryReader br = new BinaryReader(fs)) {
                    Console.WriteLine(br.ReadDecimal());
                    Console.WriteLine(br.ReadString());
                    Console.WriteLine(br.ReadString());
                    Console.WriteLine(br.ReadChar());
                }
            }
        }
    }
}

    


Uses methods in the File class to check the status of a file

image_pdfimage_print
   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Status.cs -- Uses methods in the File class to check the status of a file.
//
//              Compile this program with the following command line
//                  C:>csc Status.cs
using System;
using System.IO;

namespace nsStreams
{
    public class Status
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            if (!File.Exists (args[0]))
            {
                Console.WriteLine (args[0] + " does not exist");
                return;
            }
            DateTime created = File.GetCreationTime (args[0]);
            DateTime accessed = File.GetLastAccessTime (args[0]);
            DateTime written = File.GetLastWriteTime (args[0]);
            Console.WriteLine ("File " + args[0] + ":");
            string str = created.ToString();
            int index = str.IndexOf (" ");
            Console.WriteLine ("	Created on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
            str = accessed.ToString();
            index = str.IndexOf (" ");
            Console.WriteLine ("	Last accessed on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
            str = written.ToString();
            index = str.IndexOf (" ");
            Console.WriteLine ("	Last written on " + str.Substring (0, index) + " at " + str.Substring (index + 1));
        }
    }
}


           
          


Uses methods in the File class to check whether a file exists

image_pdfimage_print
   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/

// Exists.cs -- Uses methods in the File class to dheck whether a file exists.
//              If it exists, it then opens and reads the file to the console.
//
//              Compile this program with the following command line
//                  C:>csc Exists.cs
using System;
using System.IO;

namespace nsStreams
{
    public class Exists
    {
        static public void Main (string [] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine ("Please enter a file name");
                return;
            }
            if (!File.Exists (args[0]))
            {
                Console.WriteLine (args[0] + " does not exist");
                return;
            }
            StreamReader reader;
            try
            {
                reader = File.OpenText (args[0]);
            }
            catch (Exception e)
            {
                Console.WriteLine (e.Message);
                Console.WriteLine ("Cannot open " + args[0]);
                return;
            }
            while (reader.Peek() >= 0)
            {
                Console.WriteLine (reader.ReadLine ());
            }
            reader.Close ();
        }
    }
}


           
          


File class to check whether a file exists, open and read

image_pdfimage_print
   

/*
C# Programming Tips & Techniques
by Charles Wright, Kris Jamsa

Publisher: Osborne/McGraw-Hill (December 28, 2001)
ISBN: 0072193794
*/
// cp.cs -- Uses methods in the File class to check whether a file exists.
//          If it exists, it then opens and reads the file to the console.
//
//          Compile this program with the following command line
//              C:>csc cp.cs
using System;
using System.IO;

namespace nsStreams
{
    public class cp
    {
        static public void Main (string [] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine ("usage: cp <copy from> <copy to>");
                return;
            }
            if (!File.Exists (args[0]))
            {
                Console.WriteLine (args[0] + " does not exist");
                return;
            }
            bool bOverwrite = false;
            if (File.Exists (args[1]))
            {
                Console.Write (args[1] + " already exists. Overwrite [Y/N]? ");
                string reply = Console.ReadLine ();
                char ch = (char) (reply[0] &amp; (char) 0xdf);
                if (ch != &#039;Y&#039;)
                    return;
                bOverwrite = true;
            }
            File.Copy (args[0], args[1], bOverwrite);
        }
    }
}



           
          


illustrates the FileSystemWatcher class

image_pdfimage_print


   

/*
Mastering Visual C# .NET
by Jason Price, Mike Gunderloy

Publisher: Sybex;
ISBN: 0782129110
*/

 /*
  Example15_9.cs illustrates the FileSystemWatcher class
*/

using System;
using System.IO;

public class Example15_9 
{

  // event handler for file change
  public static void OnChanged(object source, FileSystemEventArgs e) 
  {
    // dump info to the screen
    Console.WriteLine("Change to " + e.FullPath + ": " +
     e.ChangeType);
  }

  public static void Main() 
  {

    // create a watcher for the c: drive
    FileSystemWatcher fsw = new FileSystemWatcher("c:");
    fsw.IncludeSubdirectories = true;

    // hook up the event handler
    fsw.Changed += new FileSystemEventHandler(OnChanged);

    // turn on file watching
    fsw.EnableRaisingEvents = true;
    
    // And wait for the user to quit
    Console.WriteLine("Press any key to exit");
    int i = Console.Read();

  }

}