We are continuing from where we left in System.IO. (for the first article
click) In .NET IO to write or read, we should use a stream or specific stream classes that extends abstract base class Stream. For example:
- System.IO.FileStream
- System.IO.MemoryStream
- System.Net.Sockets.NetworkStream
- System.IO.BufferedStream
In this article I'll use System.IO.FileStream to read from and write to a file. Let's look at this code:
FileStream fs = new FileStream(Server.MapPath("example.txt"), FileMode.Open);
//By using FileStream, we start to read the file. "FileMode.Open" means that this
//file will be used just for reading not another operations. Other possible values are:
//Append,Create,Truncate,CreateNew,OpenOrCreate
byte[] data = new byte[fs.Length]; fs.Read(data, 0, (int)fs.Length);
//we read the whole file by "from 0 to fs.length"
foreach (byte k in data)
{
Response.Write(k.ToString());
}
//and we send the result to the user
When we run this example, we can get some meaningless results. The reason is "FileStream" gives us the result as "byte". If we don't want to transform these bytes to human-readable form, we should use "System.IO.StreamWriter" and "System.IO.StreamReader".
StreamWriter writer = new StreamWriter(File.Open(Server.MapPath("enes.txt"), FileMode.Open));
//file.open() -->> creates a filestream for streamwriter
writer.Write("write to the file");
writer.Close();
//////////////////////////////////////////////////////////
StreamReader reader = new StreamReader(File.Open(Server.MapPath("enes.txt"), FileMode.Open));
Label1.Text = reader.ReadLine();
reader.Close();
"System.IO.StreamWriter" and "System.IO.StreamReader" creates "System.IO.FileStream" themselves (so we don't need to create them) "Label1.Text = reader.ReadLine(); " enables us to read file line by line. If we wanted to read whole file as a single chunk, we would write "Label1.Text = reader.ReadToEnd(); " Besides these methods there are other static methods in System.IO that allows us carry out these operations easier:
string k = File.ReadAllText(Server.MapPath("enes.txt"));
and
File.WriteAllText(@"C:\temp.txt",data);