How to check the name of files inside a folder
I tried what I found on this thread but didn't work exactly the way I wanted ... I have a folder called photos
it may
has pictures or not. picture name
are matriculation
clients. I need to pass matriculation
as parameter
and check if there is picture
with the name matriculation
I passed asparameter
I've tried this:
public void VerifyPhoto(string matriculation)
{
string path = Txt_PhotosPath.Text;
var file = Directory.GetFiles(path, matriculation + ".jpg");
}
How can I check if I found this image or not? I tried to compare this, file != null
but it doesn't work with type var
. Any feedback? debuging
I saw that he found a picture because there String[1]
, but I don't know, ho to check
it ...
--- Update --- path
: C: "\ Users \ admin \ Desktop \ photos" matriculation
: "607659.jpg" There is a file with that name, but it keeps returning false
, what's wrong?
string path = Txt_PhotosPath.Text;
string filename = string.Format("{0}.jpg", matriculation);
if (Directory.Exists(path))
{
if (File.Exists(Path.Combine(path, filename)))
{
return true;
}
else
return false;
}
else
return false;
source to share
Use Path.Combine
and Directory+File.Exists
:
public bool VerifyPhoto(string matriculation)
{
string dir = Txt_PhotosPath.Text;
if(Directory.Exists(dir))
{
string fileName = string.Format("{0}.jpg", matriculation);
if(File.Exists(Path.Combine(dir, fileName)))
return true;
else
return false;
}
else
return false;
}
source to share
This is what the official documentation says: http://msdn.microsoft.com/en-us/library/wz42302f.aspx
If there are no files or files do not match the searchPattern parameter, this method returns an empty array.
Thus, an empty array will be returned and instead of checking for NULL for an empty array.
source to share
Its a fairly lightweight material. The following function will help you check if the file with the name specified in the parameter exists.
File.Exists(Path)
Namespace: System.IO
This function returns true if the file exists. Otherwise, false is returned. The argument is a string, which is the complete path to validate the file. eg: G:\Folder1\Filder2\File.jpg
...
It doesn't throw any exceptions as it returns false if it finds the file.
You don't need to combine the path and that's it, just give the full path to the file as in my example.
For more information click here
source to share
To answer your question, why you can't use! = Null, it's because the underlying code for GetFiles () creates a list and calls the ToArray () extension method.
return new List<string>(FileSystemEnumerableFactory.CreateFileNameIterator(path, userPathOriginal, searchPattern, includeFiles, includeDirs, searchOption, checkHost)).ToArray();
You will need to use: -
file.Count() file.Length
source to share