Reading-Notes

File Manipulation / System I.O Notes

This topic is important to me because I think its cool that I can modify my computer files by using code.

Retrospective 3

References

File and Stream I/0

Write to a file

Read to a file

File and Stream I/O Notes

This refers to the transfer of data either to or from a storage medium.

The System.IO namespaces contain types that enable reading and writing.

You can use these types to interact with files and directories.

Here are some of the key takeaways of the library:

The .NET Standard IO library provides classes and APIs for working with input and output operations in .NET applications.

How to write to a file

The following classes and methods are typically used to write text to a file:

StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync).

File provides static methods to write text to a file such as WriteAllLines and WriteAllText, or to append text to a file such as AppendAllLines, AppendAllText, and AppendText.

Path is for strings that have file or directory path information. It contains the Combine method and in .NET Core 2.1 and later, the Join and TryJoin methods. These methods let you concatenate strings for building a file or directory path.

How to read a file

The System.IO.BinaryWriter and System.IO.BinaryReader classes are used for writing and reading data other than character strings.

    using System;
    using System.IO;

    class MyStream
    {
        private const string FILE_NAME = "Test.data";

        public static void Main()
        {
            if (File.Exists(FILE_NAME))
            {
                Console.WriteLine($"{FILE_NAME} already exists!");
                return;
            }

            using (FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew))
            {
                using (BinaryWriter w = new BinaryWriter(fs))
                {
                    for (int i = 0; i < 11; i++)
                    {
                        w.Write(i);
                    }
                }
            }

            using (FileStream fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read))
            {
                using (BinaryReader r = new BinaryReader(fs))
                {
                    for (int i = 0; i < 11; i++)
                    {
                        Console.WriteLine(r.ReadInt32());
                    }
                }
            }
        }
    }

// The example creates a file named “Test.data” and writes the integers 0 through 10 to it in binary format. // It then writes the contents of Test.data to the console with each integer on a separate line.

Things I want to know more about

How to apply this in a bigger setting (Like using it to automate your file creation etc) I want to learn how to use this for fun stuff(Deleting files if they match a certain criteria)