{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "20d84914-6c07-4829-a0c7-6ff705a33d6d",
   "metadata": {},
   "source": [
    "```{index} file; stream abstraction\n",
    "```\n",
    "\n",
    "(fileabstraction)=\n",
    "(fio)=\n",
    "\n",
    "# Files As Streams\n",
    "\n",
    "In most real world scenarios, especially in business settings, operations carried\n",
    "out with computers and information systems usually involve data processing and\n",
    "may generate new data as a result. To make the data *persistent* past the end of\n",
    "program execution, data are stored in file system or databases (for structured data). Although a\n",
    "database maybe preferred in many cases, there will be times that you need to read and write files\n",
    "for various purposes.\n",
    "\n",
    "A file is a collection of data stored on in a storage device with a name and\n",
    "directory path information. A file is stored in your file system, which is part of\n",
    "the operating system (OS), and the OS therefore has the information about the file\n",
    "and how to access it.\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9f39bd33",
   "metadata": {},
   "source": "## File Stream\n\nIn .NET, file and stream I/O (input/output) refers to the transfer of data either to or from a\nstorage medium. The System.IO namespaces contain types that enable reading and writing,\nboth synchronously and asynchronously, on data streams and files, in addition to other file and stream operations.\n\nYou have already read and written streams of\ncharacters to the `Console`. Most of the syntax that we use for files will be very similar, using\nmethods `ReadLine`, `WriteLine`, and `Write` in the same way you used them for the `Console`.\n\nWhen you read/write a file in C# program, the data processed is seen as a **Stream**.\nA stream is a sequence of bytes of data sent between the destination and the source of\nthe file. Streams are how data is read and written to and from files, networks, and\ncomputer memory. For example, printing data using a printer involves sending a sequence\nof bytes of data to a stream associated with a network port connected to the printer."
  },
  {
   "cell_type": "markdown",
   "id": "502c785d",
   "metadata": {},
   "source": "### File handling process\n\nFor file handling operations, there are two obvious streams:\n\n1.  The **Input Stream** that is used to read data from a file (read operation).\n2.  The **Output Stream** that is used to write data into a file (write operation).\n\nHowever, different task processes use different type of streams: text files, binary files,\nstrings, and network communications are some of the examples. The basic\nstream operations therefore include the following:\n\n1.  Creation/Opening\n2.  Reading\n3.  Writing\n4.  Positioning\n5.  Closing"
  },
  {
   "cell_type": "markdown",
   "id": "73f4cebe",
   "metadata": {},
   "source": "### The `System.IO` namespace\n\nFiles can be handled very differently by different operating systems, but\nC# abstracts away the differences and provides stream interfaces between\na C# program and files through the `System.IO namespace` ({ref}`namespace <namespace>`). The System.IO namespace\ncontains the required classes used to handle the input and output streams and provide information\nabout file and directory structure.\n\nThe [System.IO namespace](https://learn.microsoft.com/en-us/dotnet/api/system.io?view=net-8.0) lists all\nthe classes available for use. The [File class](https://learn.microsoft.com/en-us/dotnet/api/system.io.file?view=net-8.0)\nis one of the classes that provides static methods for the creation, copying, deletion, moving, and\nopening of a single file, and aids in the creation of FileStream objects.\n\nClasses that are commonly used to for file handling include:\n- The `FileStream` class\n- Convenience class: `File` class\n- Helper class: `StreamWriter`\n- Helper class: `StreamReader`"
  },
  {
   "cell_type": "markdown",
   "id": "9a944b83",
   "metadata": {},
   "source": "(file-class)=\n\n## Simple File Handling: `File` Class\n\nAmong the file handling methods is the convenience class `File`, which provides `static methods` for the creation,\ncopying, deletion, moving, and opening of a single file, and aids in the creation of `FileStream` objects. For example,\nthe Create(), WriteAllText, ReadAllText() and File.Exists() can be used to perform basic file operations\namong other methods:\n\n**Methods in File Class**\n\n| Method | Description |\n|--------|-------------|\n| `AppendText()` | Appends text at the end of an existing file |\n| `Copy()` | Copies a file |\n| `Create()` | Creates or overwrites a file |\n| `Delete()` | Deletes a file |\n| `Exists()` | Tests whether the file exists |\n| `ReadAllText()` | Reads the contents of a file |\n| `Replace()` | Replaces the contents of a file with the contents of another file |\n| `WriteAllText()` | Creates a new file and writes the contents to it. If the file already exists, it will be overwritten. |\n\nSine class `File` provides `static methods`, we can `call` the methods directly by using the `dot notation`\nwithout having to create a new instance of the class. For example, with `File` class, when you want to write\nsome content to a file, you can simply say `File.ReadAllText(string path, string content)` to write the\nstring content to the path file.\n\nYou should perform tests such as the following in `csharprepl` to get familiar with the methods:\n\n1.  Create a file using `File.Create (path)`: // path means filename + the file's directory path\n\n        > File.Create(\"MyTest.txt\");\n\n2.  Check if a file exists using `File.Exists (path)`:\n\n        > if (File.Exists(\"MyTest.txt\"))\n          {\n             Console.WriteLine(\"MyTest.txt exists\");\n          }\n        MyTest.txt exists\n\n3.  Write to a file using `File.WriteAllText (path, content)`:\n\n        > File.WriteAllText(\"MyTest.txt\", \"Hello, this is a test.\");\n\n4.  Read from a file using `File.ReadAllText(path)`:\n\n        > File.ReadAllText(\"MyTest.txt\");\n\n        > Console.WriteLine(File.ReadAllText(\"MyTest.txt\"));\n        Hello, this is a test.\n\n        >\n\nTo better organize the tests above, you should copy your tests in `csharprepl` and use VS Code. You should\nalso use a variable for the filename:"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d3440b72",
   "metadata": {
    "language_info": {
     "name": "polyglot-notebook"
    },
    "polyglot_notebook": {
     "kernelName": "csharp"
    }
   },
   "outputs": [],
   "source": [
    "using System;\n",
    "using System.IO;\n",
    "\n",
    "namespace IntroCSCS\n",
    "{\n",
    "internal class Ch07File\n",
    "{\n",
    "private static void Main(string[] args)\n",
    "{\n",
    "\n",
    "            // create a file\n",
    "            string path = \"MyTest.txt\";      // create the file in this directory\n",
    "            // File.Create(path);            // let WriteAllText create the file //\n",
    "                                             // File.Create() does not close file; leads to exception\n",
    "\n",
    "            // test file existence\n",
    "            if (File.Exists(path))\n",
    "            {\n",
    "               Console.WriteLine($\"The file {path} exists.\");\n",
    "            }\n",
    "\n",
    "            // write to the file\n",
    "            string str = \"Hello, I know how to writing files.\";\n",
    "            File.WriteAllText(path, str);    // static method WriteAllText() will create the file if not exists\n",
    "\n",
    "\n",
    "            // read the file\n",
    "            string s = File.ReadAllText(path);  // static method ReadAllText() for reading from file\n",
    "            Console.WriteLine(s);\n",
    "\n",
    "      }\n",
    "\n",
    "}\n",
    "}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "footnotes",
   "metadata": {},
   "source": [
    "```{rubric} Footnotes\n",
    "```\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": ".NET (C#)",
   "language": "C#",
   "name": ".net-csharp"
  },
  "language_info": {
   "name": "polyglot-notebook"
  },
  "polyglot_notebook": {
   "kernelInfo": {
    "defaultKernelName": "csharp",
    "items": [
     {
      "aliases": [],
      "name": "csharp"
     }
    ]
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}