1

So i have this function

    public bool FileExists(string path, string filename)
    {
        string fullPath = Path.Combine(path, "pool");
        string[] results = System.IO.Directory.GetFiles(fullPath, filename, SearchOption.AllDirectories);
       return (results.Length == 0 ?  false : true);
    }

And it returns true or false on whether a file is found in a directory and all its subdirectories...But i want to pass the string location as well

Here is how i call it

            if (FileExists(location, attr.link))
            {
                FileInfo f = new FileInfo("string the file was found");

Any ideas on how to achieve this? Maybe change to a list or array ...any ideas

4

6 回答 6

5

你的意思是你只想返回找到文件的所有位置吗?

你可以这样做:

public static string[] GetFiles(string path, string filename)
{
    string fullPath = Path.Combine(path, "pool");
    return System.IO.Directory.GetFiles(fullPath, filename, SearchOption.AllDirectories);   
}

并像这样使用:

var files = GetFiles(location, attr.link);

if (files.Any())
{
    //Do stuff
}
于 2012-05-16T13:52:01.940 回答
4

因此将方法重命名为TryFindFile并提供签名:

public bool TryFindFile(string path, string filename, out string location)

true如果找到该文件,则该方法返回,并设置location为该位置,否则返回false并设置locationnull. 如果有多个位置,您可以键入locationa 。string[]

于 2012-05-16T13:48:33.203 回答
0

各种方式 - 返回具有两个字段的结构或类,使用out关键字修改,使用Tuple

于 2012-05-16T13:49:33.700 回答
0

你可以使用一个out参数?

public bool FileExists(string path, string filename, out string location)
{
    string fullPath = Path.Combine(path, "pool");
    string[] results = System.IO.Directory.GetFiles(fullPath, filename, SearchOption.AllDirectories);
    var doesExist = (results.Length == 0 ?  false : true);
    location = fullPath;//or whatever it is
}

然后你可以这样称呼它

if (FileExists(path, filename, out location))
{
    //location now holds the path
}

更多关于out参数的信息可以在这里找到。

于 2012-05-16T13:50:06.953 回答
0

添加您需要的参数。

bool FileExists(string path, string filename, out string somthElse)
{
   somthElse = "asdf";
   return true;
}
于 2012-05-16T13:48:15.547 回答
0

您可以将输出参数(out string[] results)传递给方法并保留该方法,或者您可以更改方法并返回结果数组(并在调用者中检查 true 或 false)。

更便宜的做法是添加一个 out 参数。

于 2012-05-16T13:49:22.250 回答