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

Do you mean you just wish to return all of the occurrences of where the file was found?

You can just do:

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

And use like so:

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

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

Rename the method to TryFindFile and provide with the signature thusly:

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

The method returns true if it found the file, and sets location to the location, otherwise it returns false and sets location to null. You can type location as a string[] if there are multiple locations.

于 2012-05-16T13:48:33.203 に答える
0

Add out parameter that you need.

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

You can pass an output parameter (out string[] results) to the method and keep the method or you can change the method and return the array of results (and check the true or false in the caller).

The cheaper thing to do is to add an out parameter.

于 2012-05-16T13:49:22.250 に答える
0

Various ways- return a struct or a class with two fields, use out keyword modified, use a Tuple.

于 2012-05-16T13:49:33.700 に答える
0

You could use an out parameter?

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
}

You can then call it thusly

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

More info on out parameter can be found here.

于 2012-05-16T13:50:06.953 に答える