I am very new to C# and i have written the following class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace PrinterManager
{
class CheckFilesExist
{
public class CheckFilesExist
{
public static bool check(bool isThere)
{
DirectoryInfo di = new DirectoryInfo("c:\temp");
FileInfo[] TXTFiles = di.GetFiles("*.xml");
if (TXTFiles.Length == 0)
{
return isThere;
}
foreach (var fi in TXTFiles)
//return (fi.Exists);
return (fi.Exists);
return check;
}
}
}
}
It should check the directory for *.xml files and add them to an array. If it doesnt find any files then it should return false. It will go through the array and return true or false based on "check".
But i am getting the following error:
Cannot convert method group 'check' to non-delegate type 'bool'. Did
you intend to invoke the method?
It doesnt seem to like, "return check;" at the end.
I basically want to return a check to see if files exists in the folder.
Any ideas why mine isnt working?
Thanks
No, it doesn't like return check;
at the end - what did you want it to do? Your method is check
- so "return true or false based on check
" doesn't really make sense. Did you actually mean to return isThere
instead?
It's not clear what the parameter is even really meant to be there for, to be honest... and if you've asked a DirectoryInfo
for the files in that directory, I'd personally expect them to exist - otherwise why would they be returned?
Oh, and your directory name contains a tab where I suspect you actually want a backslash followed by a t
.
I suspect your method would be better as:
public static bool TempDirectoryContainsXmlFiles()
{
DirectoryInfo di = new DirectoryInfo(@"c:\temp");
return di.GetFiles("*.xml").Length > 0;
}
or using LINQ for clarity:
public static bool TempDirectoryContainsXmlFiles()
{
DirectoryInfo di = new DirectoryInfo(@"c:\temp");
return di.GetFiles("*.xml").Any();
}
(You can use EnumerateFiles
as shown by BrokenGlass which is more efficient for a large directory, but it's only available in .NET 4 and upwards.)
You can make a one-liner out of your method:
return new DirectoryInfo(@"c:\temp").EnumerateFiles("*.xml").Any();
Note that you are either have to use a literal string (prefixed by @
) or properly escape the directory name, i.e. "C:\\temp"
.
At a first glance, the problem as to be with the fact of your "check" variable having the same name as your function...
try like this....
private static bool Check_file_Existence(string sFileName)
{
try
{
return File.Exists(sFileName);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}