Core C#

Check Whether a File Exists

This C# program demonstrates how to check whether a file with a given filename exists.

Program.cs

using System;
using System.IO;

namespace XoaX {
    class Program {
        static void Main(string[] args) {
            // Local file names
            string[] saFilenames = { @"XoaX.net", @"XoaX.exe", @"XoaX.txt" };
            foreach (string sFileName in saFilenames) {
                Console.WriteLine("The file " + sFileName +
                    (File.Exists(sFileName) ? " does " : " does not ") + "exist.");
            }

            // File names and paths. Note: the first directory is not a file
            string[] saFilepaths = { @"C:\temp", @"C:\temp\MyXsd.cs" };
            foreach (string sFilepath in saFilepaths) {
                Console.WriteLine("The file " + sFilepath +
                    (File.Exists(sFilepath) ? " does " : " does not ") + "exist.");
            }
        }
    }
}
 

Output

The file XoaX.net does not exist.
The file XoaX.exe does exist.
The file XoaX.txt does not exist.
The file C:\temp does not exist.
The file C:\temp\MyXsd.cs does exist.
Press any key to continue . . .
 
 

© 2007–2024 XoaX.net LLC. All rights reserved.