Loading the lesson...
In the print dialog, choose "Save as PDF" as the destination.
Operating Systems 1 - Lab
Building a Linux-style file emulator on top of FileStream, StreamReader and StreamWriter, one shell command at a time.
System.IO.Stream is the base class for every stream in .NET.FileStream reads and writes files on diskMemoryStream holds the same bytes in memory insteadNetworkStream carries them over a network connectionvar fs = File.Create(name);
fs.Close(); // Important: always close the stream after useFile.Create hands back an open FileStream, and the handle stays held until you close it.private static void Rm()
{
var name = Console.ReadLine();
if (!ValidateExists(name)) return;
File.Delete(name);
}var content = File.ReadAllText(name);
Console.WriteLine(content);
File.AppendAllText(name, text);ReadAllText returns the whole file as one stringAppendAllText writes to the end without disturbing what is already thereFileStream fs = new FileStream(name, FileMode.OpenOrCreate, FileAccess.ReadWrite);
StreamReader sr = new StreamReader(fs);
sr.BaseStream.Seek(0, SeekOrigin.Begin);
string str = sr.ReadLine();FileStream fs = new FileStream(name, FileMode.Create, FileAccess.ReadWrite);
StreamWriter w = new StreamWriter(fs);
w.Write(text);
w.Flush();
w.Close();
fs.Close();StreamWriter, then the FileStream underneath it.| Mode | What it does |
|---|---|
CreateNew | creates a new file, and throws if one already exists |
Create | creates a new file, overwriting an existing one |
Open | opens an existing file, and throws if it is missing |
OpenOrCreate | opens it if present, creates it if not |
Truncate | opens it and clears the existing content |
Append | opens it and moves the position to the end |
Read grants read-only access to the streamWrite grants write-only accessReadWrite grants both on the same streamprivate static bool ValidateExists(string? name)
{
if (string.IsNullOrEmpty(name)) return false;
if (!File.Exists(name)) return false;
return true;
}using statement so the close happens when the block ends, exception or notFlush when a write must reach disk immediatelyFileStream is the low-level file class, and the reader and writer add text convenience on topFile.ReadAllText, File.AppendAllText and File.Create manage a stream internally for youFileMode decides how the file is opened, and FileAccess decides what the stream may doFlush when a write has to hit disk nowMahmoud Abas|Lab: File Streams in C#