Background
Many times I have read one question in our communnity forum, which is "How to create files on a local drive using C# ?", so by considering the above requirement I have decided to write this article. So let us start with the basics.
What is a file ?
A file is nothing but a collection of meaningful data with systematically organized information. All the file-related operations are done in the .Net framework using classes in the System.IO namespace.
So let us start step-by-step
- Create one foder on the System's local D drive named FilesCreated to store the files, as:
D:\FilesCreated
2. Create the sample console application to create the files as follows:
- Open Visual Studio from Start - - All programs -- Microsoft Visual Studio.
- Then go to to "File" -> "New" -> "Project..." then select Visual C# -> Windows -> Console application.
- After that specify the name such as CreateFiles or whatever name you wish and the location of the project and click on the OK button. The new project is created.
Now use the following code in the Program.cs file to create various files.
In the above code:
StreamWriter: is used to write the files
String Filename: Is used to specify the location to store the created files
String Filedata: Is used to to store the contents of the files to be printed
Now run the application, then the text file named CsharpcornerDemo is created at the location D:\FilesCreated; open it. It will look as in the following:
Now run the application, then the Word file named CsharpcornerDemo is created at the location D:\FilesCreated; open it. It will look as in the following:
Now run the application. The Excel file named CsharpcornerDemo is thne created at the location D:\FilesCreated; open it. It will look as in the following:
Now run the application. The PDF file named CsharpcornerDemo is then created at the location D:\FilesCreated. Similarly open it as above.
Summary
I hope this article is useful for all readers, if you have any suggestion then please contact me.