在c#windows应用程序中查找文件夹的路径

时间:2013-11-20 06:17:06

标签: c# asp.net

我需要找到文件夹的路径。假设文件夹名称为Test。如果我的应用程序安装在c:\drive上,那么在这种情况下Test文件夹可以位于c:\drive中的任何级别,而我需要路径的页面也可以位于{{1}中的任何级别}}

谢谢你的帮助。

3 个答案:

答案 0 :(得分:1)

试试这个。

static void Main(string[] args)
    {

       string pathToDirctory = @"C:\\";
       string baseDirectory = pathToDirctory;


       string path = SearchAllFolders(pathToDirctory,"Test");


    }

    private static string SearchAllFolders(string path, string search)
    {
        string folderPath = string.Empty;
        try
        {
            if ((File.GetAttributes(path) & FileAttributes.ReparsePoint)
                != FileAttributes.ReparsePoint)
            {
                foreach (string folder in Directory.GetDirectories(path))
                {
                    if (folder.Contains("RECYCLE.BIN"))
                    {
                        continue;
                    }
                    string p = Path.GetFileName(folder);

                    if ( p.Equals(search))
                    {
                        return folder;
                    }
                    else
                    {
                        string f = SearchAllFolders(folder ,search);
                        if (f != null)
                        {
                            return f;
                        }
                    }

                }
            }
        }
        catch (UnauthorizedAccessException) { }

        return null;
    }

答案 1 :(得分:0)

您可以尝试使用递归函数按名称查找文件夹:

http://support.microsoft.com/kb/303974

答案 2 :(得分:0)

在asp.net Web应用程序中编写代码时尝试使用此代码

string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;
foreach (string dir in Directory.GetDirectories(baseDirectory, "Test", SearchOption.AllDirectories)) 
{
    // dir will be a path of "Test" folder.
    // You will get more than one path if it found more than one folder names Test.
}

baseDirectory 将存储您安装应用程序的文件夹的路径。