Introduction
File handling is a term used in almost all programming languages. Its basic purpose is to cope with or deal with the files. In every large and complex programs it is used. When you develop some enterprise-level applications then you have to handle the files. This small article tells you the basics of file handling and also tells you how to perform simple write operation in file handling.
Of course most people are competent in programming, but when someone says to handle a file then they give horrible expressions. Because when you're in colleges and universities you've learned some basic concepts of programming such as loop, what is array, who loop works, what are data types, variables, functions etc. File handling is an advanced concept. But don't worry we'll go through this complex task in few chunks quite easily.
Before I get started I'll give you a brief introduction of file handling. As the name suggests we'll handle some basic operations i.e., writing to file, reading from file etc. during file handling.
So let’s get started.
First of all you'll need to create a Console Application in Visual Studio and name it whatever you want.
Now after this you will create two string variables. One is for giving input to the console and the other is for holding the console input and creates into the output of the text file.
- string firstname;
- string outline;
-
- Console.WriteLine("Enter your name");
-
- firstname = Convert.ToString( Console.ReadLine());
- outline = firstname;
After this declare a string variable to hold the path name of the file with extension .txt.
- string path = @"filename2.txt";
Now what you'll need is simply to create a if condition to check if the file already exists, then you'll create a new file with the help of the following line of code.
- if (!File.Exists(path))
- {
- using (StreamWriter sw = File.CreateText(path))
- {
- sw.WriteLine(outline);
- }
-
- }
After this simply write Console.ReadKey() operation.
Now run your application and type something in the console window. Now go to the location of your project where you store all your projects and find your project, whatever name you provide, and into the Debug folder you will find a bin folder; open it and here you will find your filename with .txt extension. Open it and you'll notice that whatever you had written in your console window is simply stored here.
Boom! Now after reading this article and with some practice when someone says to you, "What is that file handling?" then you'll tell him/her quite easily.
See you again with an advanced and tricky article. Until then practice and give time to your programming.