- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if a File exists in C#
Use the File.exists method in C# to check if a file exits in C# or not.
Firstly, check whether the file is present in the current directory.
if (File.Exists("MyFile.txt")) { Console.WriteLine("The file exists."); }
After that check whether the file exist in a directory or not.
if (File.Exists(@"D:\myfile.txt")) { Console.WriteLine("The file exists."); }
Let us see the complete example to check if a file exists in C#.
Example
using System; using System.IO; class Demo { static void Main() { if (File.Exists("MyFile.txt")) { Console.WriteLine("File exists..."); } else { Console.WriteLine("File does not exist in the current directory!"); } if (File.Exists(@"D:\myfile.txt")) { Console.WriteLine("File exists..."); } else { Console.WriteLine("File does not exist in the D directory!"); } } }
Output
File does not exist in the current directory! File does not exist in the D directory!
Advertisements