Getsuyodev, Programming is mainly used when constructing an application. Programming requires knowledge of application domains, algorithms, and programming language expertise. Programming can be developed in different logic based on developer knowledge.

How to use C Sharp File Class



File class is using for the File operations in C#. We can create, delete, copy etc. operations do with C# File class.

How to create a File using C# File class?

In order to create a new File using C# File class, we can call Create a method in the File class.

Syntax

FileSttream File.Create(string FilePath)
  • FilePath: The name of the new File Object
 
File.Create("c:\\testFile.txt");

How to check a File exist or not using C# File class?

Before we are creating a File object, we usually check that File exist or not. For that, we are using the Exists method in the C# File class.

Syntax

bool File.Exists(string FilePath)
  • FilePath: The name of the File
  • bool: Returns true or false
File.Exists("c:\\testFile.txt")

The following C# source code shows these operations :

using System;
using System.Windows.Forms;
using System.IO;

namespace WindowsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
			if (File.Exists("c:\\testFile.txt"))
			{
				//shows message if testFile exist 
				MessageBox.Show ("File 'testFile' Exist ");
			}
			else
			{
				//create the file testFile.txt 
				File.Create("c:\\testFile.txt");
				MessageBox.Show("File 'testFile' created ");
			}
        }
    }
}

Comments are closed.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More