How do I create a file using File or FileInfo class?

Category: System.IO, viewed: 302 time(s).

To create a file we can either use the File.Create(string fileName) or using the FileInfo's Create() method. The different between these two classes is that File.Create() is provided as a static method. While creating a file using FileInfo class required us to create an instance of FileInfo class. Both this method return a FileStream as the result the create method.

using System;
using System.IO;

namespace Kodecsharp.Example.System.IO
{
	class FileCreateDemo
	{
        [STAThread]
        public static void Main(string[] args) {
            //
            // The name of file to be created.
            //
            string fileName1 = @"c:\Users\me\demo1.txt";
            string fileName2 = @"c:\Users\me\demo2.txt";

            //
            // File.Create() method return a FileStream that can be used
            // to write some data to the file.
            //
            FileStream stream = File.Create(fileName1);

            //
            // We can also use the FileInfo class to create a file. It 
            // also return a FileStream object.
            //
            FileInfo fi = new FileInfo(fileName2);
            FileStream fs = fi.Create();
        }
	}
}
Download Hundreds of Complimentary Industry Resources

Get hundreds of popular Industry magazines, white papers, webinars, podcasts, and more; all available at no cost to you. With more than 600 complimentary offers, you'll find plenty of titles to suit your professional interests and needs. Click Here and Sign up today!

Our Friends

Statistics

Locations of visitors to this page