How to check if a file exists in a folder?

2019-01-06 11:24发布

I need to check if an 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")
}

Is this the best way to check a file exists in the folder.

I need to check just an xml file is present

9条回答
不美不萌又怎样
2楼-- · 2019-01-06 11:47

It can be improved like so:

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

Alternatively:

log.Info(Directory.EnumerateFileSystemEntries(ProcessingDirectory, "*.xml").ToList<string>().Count + " file(s) present");
查看更多
家丑人穷心不美
3楼-- · 2019-01-06 11:51

This is a way to see if any XML-files exists in that folder, yes.

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

查看更多
做自己的国王
4楼-- · 2019-01-06 11:52

Since nobody said how to check if the file exists AND get the current folder the executable is in (Working Directory):

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

The @"\YourFile.txt" is not case sensitive, that means stuff like @"\YoUrFiLe.txt" and @"\YourFile.TXT" or @"\yOuRfILE.tXt" is interpreted the same.

查看更多
The star\"
5楼-- · 2019-01-06 11:56

To check file exists or not you can use

System.IO.File.Exists(path)
查看更多
相关推荐>>
6楼-- · 2019-01-06 11:58
if (File.Exists(localUploadDirectory + "/" + fileName))
{                        
    `Your code here`
}
查看更多
Ridiculous、
7楼-- · 2019-01-06 12:04

This helped me:

bool fileExists = (System.IO.File.Exists(filePath) ? true : false);
查看更多
登录 后发表回答