Working with Files in c# – intoduction

Here are some of many classes available to work with files

using TextReder and TextWriter classes

string filePath = @"E:\TestDocument.txt";

// open file to read
TextReader tr = File.OpenText(filePath);
Console.WriteLine(tr.ReadToEnd());

// must close file after reading
tr.Close();

string filePath = @"E:\TestDocument.txt";

// open file to read
TextReader tr = File.OpenText(filePath);
Console.WriteLine(tr.ReadToEnd());

// must close file after reading
tr.Close();

using StreamReader and and StreamWriter classes

// open file to read file 
StreamReader sr = new StreamReader(filePath); 
Console.WriteLine(sr.ReadToEnd());

// must close file after writing
sr.Close();

// open file to write
StreamWriter sw = new StreamWriter(filePath);
sw.AutoFlush = true;
Console.WriteLine(sw.Encoding);
Console.WriteLine(sw.FormatProvider);
sw.WriteLine("Hello World");

// must close file after writing
sw.close()

Reading / writing To IsolatedStorageFile using IsolatedStorageFileStream

// declare file IsolatedStorageFile
IsolatedStorageFile isoStore = 
IsolatedStorageFile.GetUserStoreForAssembly();

// create file Stream
IsolatedStorageFileStream isoFS =
                new IsolatedStorageFileStream("temp.txt", FileMode.Create, FileAccess.Write);

// write to file
sw = new StreamWriter(isoFS);
sw.WriteLine("in iso storage" + "\n");           
sw.WriteLine("in iso storage FInished");

// must remember to close or the resouce is kept locked
sw.Close();

// read from IsolatedStorageFile
isoFS = new IsolatedStorageFileStream("temp.txt", FileMode.Open, FileAccess.Read);
sr = new StreamReader(isoFS);
Console.WriteLine(sr.ReadToEnd());