Create Text Word Excel and PDF File Using C# Console Application

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
  1. 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:
  1. Open Visual Studio from Start - - All programs -- Microsoft Visual Studio.
  2. Then go to to "File" -> "New" -> "Project..." then select Visual C# -> Windows -> Console application.
  3. 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.
  • To Create Text Files:
codefortext.pngcodefortext.png
 
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:
 
Textfileoutput.png
  • To Create Word File:
wordFilecode.png
 
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:
 
Wordfileoutput.png
  • To Create Excel Files:
Excelfilecode.pngExcelfilecode.png
 
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:
 
Excelfileoutput.png
  • To create a PDF File:
Pdffilecode.png
 
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.


Similar Articles