C sharp file I/O methods are in namespace called System.IO. C sharp file handling implies files listing, files and folders creation, writing down and reading from file. Here is the code for listing folder:
static void Main(string args)
string str_content = Directory.GetDirectories(@”D:\”);
foreach(string str_filename in str_content )
Given code has the similar effect as MS DOS command dir d:\. Since size of an array must be declared together with array declaration, only solution was to give all of the strings into array by using object Directory from System.IO namespace. Content was displayed in foreach loop with string str_filename as enumerated parameter.
We can also write some data into the file by using StreamWriter object as reference to file.
StreamWriter myFile; // reference to file
myFile = File.CreateText(“example.txt”);
myFile.WriteLine(“Have a nice day :-)”);
Data can also be read from the file, but since we can’t be sure whether file opening operation will be successful or not, we need to use C sharp try-catch exception handling structure:
string all_lines = File.ReadAllLines(“example.txt”);
foreach(string str_line in all_lines)
Console.WriteLine(“There is no such file”);
C sharp file I/O will be explained in more details with Windows form examples.