How to make a text document creator with error catching C#

[By JayDev64x] [Index]

Creating a console document creator is very simple but opens up a lot since text files can be used to store data and the combination with exception catching is also very important to know since programs can be prevented from crashing despite having runtime errors. This program uses the functions built-in with System.IO to create a very simple document creator that is capable of deleting, editing, creating, and reading text files.

using System; using System.IO; namespace Script { class Example { void Selection() { Console.WriteLine("Options: [create] [edit] [read] [delete]"); string option = Console.ReadLine(); Console.Clear(); if (option == "create") { Create(); } else if (option == "edit") { Edit(); } else if (option == "read") { Read(); } else if (option == "delete") { Delete(); } else { Console.WriteLine("This is not a valid option."); } Selection(); } // Used for creating a text file. void Create() { Console.WriteLine("Please enter the text file's name."); string file = Console.ReadLine(); // Checks for a invalid path to prevent crashing. try { File.CreateText(file + ".txt").Close(); } catch (IOException) { Console.WriteLine("Error: Path was invalid. | Press enter to proceed."); Console.ReadLine(); Selection(); } Console.Clear(); Selection(); } // Used for editing the contents of a text file. void Edit() { Console.WriteLine("Please enter the text file's path."); string file = Console.ReadLine(); Console.WriteLine("Please enter the text you want added to the document."); string text = Console.ReadLine(); try { File.WriteAllText(file + ".txt", text); } catch (IOException) { Console.WriteLine("Error: Path was invalid. | Press enter to proceed."); Console.ReadLine(); Selection(); } Console.Clear(); Selection(); } // Used for reading the contents of a text file. void Read() { Console.WriteLine("Please enter the text file's path."); string file = Console.ReadLine(); try { Console.WriteLine(File.ReadAllText(file + ".txt")); } catch (IOException) { Console.WriteLine("Error: Path was invalid. | Press enter to proceed."); Console.ReadLine(); Selection(); } Console.WriteLine("Press enter to proceed."); Console.ReadLine(); Console.Clear(); Selection(); } // Used for deleting a text file. void Delete() { Console.WriteLine("Please enter the text file's path."); string file = Console.ReadLine(); try { File.Delete(file); } catch(IOException) { Console.WriteLine("Error: Path was invalid. | Press enter to proceed."); Console.ReadLine(); Selection(); } Console.Clear(); Selection(); } // Takes the program out of a static function. static void Main() { Example example = new Example(); example.Selection(); } } }

Created [September 6, 2021]