How to check if a file exists in a folder?

I need to check if the xml file exists in the folder.

DirectoryInfo di = new DirectoryInfo(ProcessingDirectory); FileInfo[] TXTFiles = di.GetFiles("*.xml"); if (TXTFiles.Length == 0) { log.Info("no files present") } 

This is the best way to check the file in the folder.

I need to check only the xml file is present

+63
c # xml file fileinfo
Sep 12 '11 at 8:41
source share
8 answers

This is a way to see if any XML files exist in this folder, yes.

To check for specific files, use File.Exists(path) , which will return a boolean value indicating that the file exists in path .

+113
Sep 12 '11 at 8:44
source share

Use the FileInfo.Exists Property:

 DirectoryInfo di = new DirectoryInfo(ProcessingDirectory); FileInfo[] TXTFiles = di.GetFiles("*.xml"); if (TXTFiles.Length == 0) { log.Info("no files present") } foreach (var fi in TXTFiles) log.Info(fi.Exists); 

or File.Exists Method:

 string curFile = @"c:\temp\test.txt"; Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist."); 
+25
Sep 12 '11 at 8:44
source share

To check if a file exists or not, you can use

 System.IO.File.Exists(path) 
+20
Sep 12
source share

Thus, we can check the existing file in a specific folder:

  string curFile = @"c:\temp\test.txt"; //Your path Console.WriteLine(File.Exists(curFile) ? "File exists." : "File does not exist."); 
+6
Sep 02 '14 at 5:48
source share

Since no one said how to check if the file exists AND get the current folder in which the executable file is located (Working directory) :

 if (File.Exists(Directory.GetCurrentDirectory() + @"\YourFile.txt")) { //do stuff } 

@"\YourFile.txt" not case sensitive, which means that things like @"\YourFile.txt" and @"\YourFile.txt" or @"\YourFile.txt" are interpreted the same way.

+3
Feb 24 '16 at 21:31
source share

It can be improved like this:

 if(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count == 0) log.Info("no files present") 

As an alternative:

 log.Info(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count + " file(s) present"); 
+2
Mar 08 '16 at 12:37
source share

It helped me:

 bool fileExists = (System.IO.File.Exists(filePath) ? true : false); 
0
Sep 06 '17 at 8:19 on
source share
  String^ fileName = "C:\\Cal_Connect\\" + (this->cbo_Model_Name->Text) + "\\" + (this->txt_Certificate_No->Text) + "\\CUSTOMER RECORD\\" + "Status" + ".txt"; // สร้าง file CUSTOMER RECORD if (!System::IO::File::Exists(fileName)) /* ถ้าไม่มี file จะสร้าง file ใหม่ (ถ้ามีจะไม่สร้าง file) */ 
-9
Sep 06 '16 at 2:46 on
source share



All Articles