Question #44510

Describe the different methods of the classes that Elina would be using to implement file input
and output operations in the application

Expert's answer

ANSWER ON QUESTION #44510, Programming, C#

Most of the classes that can provide file input/output operation can be found in the System.IO namespace. They are:

- FileStream

- StreamReader

- StreamWriter

- And other

class FileStream:

First we need to create object of the class (There are 15 different overloads to get an object):


FileStream fs = new FileStream("D:\\test.txt", FileMode.Open, FileAccess.ReadWrite);


Where first argument is the path to the file, second – file mode (open, create ...), third – file access(read, write, read and write).

After it we can read/write information to/from the file via the next methods:


fs.Write(); // Three argument are required: byte[] information, int offset, in count
fs.Read(); // Three argument are required: byte[] information, int offset, in count


There is an example how to do it:


FileStream fs = new FileStream("D:\\test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite);
string content = "Some information";
fs.Write(Encoding.ASCII.GetBytes(content), 0, content.Length); //writing
byte[] buffer = new byte[content.Length]; // array for save inforamtion from file
fs.Seek(0, SeekOrigin.Begin); // set pointer to the start of file
fs.Read(buffer, 0, buffer.Length); // reading
fs.Close(); // don't forget to close the file
for (int i = 0; i < buffer.Length; i++) // output
    Console.Write((char)buffer[i]);


FileStream class is universal class to read and write information to/from the file. All other classes provide only reading or writing information.

class StreamWriter and StreamReader:


StreamWriter swt = new StreamWriter("D:\\test.txt");
swt.Write("content");
swt.WriteLine("content");
swt.Close();
StreamReader str = new StreamReader("D:\\test.txt");
string buff = "";
str.Read(buff.ToCharArray(), 0, buffer.Length);


http://www.AssignmentExpert.com/

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS