Electronic and Electric Circuit Simulation
Home C Sharp Code Examples c sharp file handling
c sharp file handling PDF Print E-mail


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:

using System.IO;
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("Hello World!");
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.

<< Previous reading Next reading >>

External links:

C Sharp File Handling on Dotnetperls
C Sharp File Handling on tutorialspoint
C Sharp File Handling on Microsoft
C Sharp File Handling on CSharp-station

Copyright © 2015 Electronic and Electric Circuit Simulation. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License. Top joomla 1.5 themes
Top joomla 1.5 themes designed by Lonex.

Recent/Mostly Visited

Simulate recent1: Op-Amp Differential Amplifier

Simulate recent2: Relaxation Oscillator

Simulate recent3: Differential Amplifier