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());
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s