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

Category: System.IO, viewed: 1K 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();
        }
	}
}
Powered by Disqus