C# 从要列出的文件夹中获取文件,将子目录添加到下拉列表中,并在列表中列出文件名

C# 从要列出的文件夹中获取文件,将子目录添加到下拉列表中,并在列表中列出文件名,c#,file,loops,combobox,listbox,C#,File,Loops,Combobox,Listbox,先看一下这个屏幕截图,看看会发生什么: 你在这个截图上看到的是我已经做过的。。但我想补充几点 现在,单击“添加到列表”按钮,所有具有完整路径的文件都存储在列表A中。它们的文件名存储在列表B中。下面是代码: if (type == "folder") { string listPath = this.configsPath.Text; string[] filesToList = S

先看一下这个屏幕截图,看看会发生什么:

你在这个截图上看到的是我已经做过的。。但我想补充几点

现在,单击“添加到列表”按钮,所有具有完整路径的文件都存储在列表A中。它们的文件名存储在列表B中。下面是代码:

 if (type == "folder")
                {
                    string listPath = this.configsPath.Text;
                    string[] filesToList = System.IO.Directory.GetFiles(listPath, "*.*", System.IO.SearchOption.AllDirectories);
                    foreach (string file in filesToList)
                    {
                        if (!configsChkList.Items.Contains(file))
                        {
                            configsChkList.Items.Add(file, false);
                            configsDestList.Items.Add(Path.GetFileName(file));
                        }
                    }
                }
我希望列表b也存储它们相对于输入字段中指定的路径的路径。。例如,列表A中的最后三个条目位于名为“undermappe”的子目录中,但由于我使用Path.GetFileName将条目存储在列表B中,因此无法查看子目录。。我该怎么做

还有一件事。子目录也应该存储在顶部的组合框中,但只存储目录而不是名称!我怎样才能做到这一点呢?

我没有写这篇文章(所以我不相信),但是这个函数返回相对路径:

    /// <summary>
    /// method to provide a relative path from a directory to a path
    /// </summary>
    /// <param name="fromDirectory">the starting folder</param>
    /// <param name="toPath">the path that will be pointed to</param>
    /// <returns>string</returns>
    public static string RelativePathTo(string fromDirectory, string toPath)
    {

        if (fromDirectory == null)
        {
            throw new ArgumentNullException("fromDirectory");
        }

        if (toPath == null)
        {
            throw new ArgumentNullException("fromDirectory");
        }

        if (System.IO.Path.IsPathRooted(fromDirectory) && System.IO.Path.IsPathRooted(toPath))
        {

            if (string.Compare(System.IO.Path.GetPathRoot(fromDirectory)
                , System.IO.Path.GetPathRoot(toPath), true) != 0)
            {
                throw new ArgumentException(
                    String.Format("The paths '{0} and '{1}' have different path roots."
                        , fromDirectory
                        , toPath));
            }

        }

        StringCollection relativePath = new StringCollection();
        string[] fromDirectories = fromDirectory.Split(System.IO.Path.DirectorySeparatorChar);
        string[] toDirectories = toPath.Split(System.IO.Path.DirectorySeparatorChar);

        int length = Math.Min(fromDirectories.Length, toDirectories.Length);
        int lastCommonRoot = -1;

        // find common root
        for (int x = 0; x < length; x++)
        {
            if (string.Compare(fromDirectories[x], toDirectories[x], true) != 0)
            {
                break;
            }

            lastCommonRoot = x;

        }

        if (lastCommonRoot == -1)
        {

            throw new ArgumentException(
                string.Format("The paths '{0} and '{1}' do not have a common prefix path."
                    , fromDirectory
                    , toPath));
        }

        // add relative folders in from path
        for (int x = lastCommonRoot + 1; x < fromDirectories.Length; x++)
        {
            if (fromDirectories[x].Length > 0)
            {
                relativePath.Add("..");
            }
        }

        // add to folders to path
        for (int x = lastCommonRoot + 1; x < toDirectories.Length; x++)
        {
            relativePath.Add(toDirectories[x]);
        }

        // create relative path
        string[] relativeParts = new string[relativePath.Count];
        relativePath.CopyTo(relativeParts, 0);
        string newPath = string.Join(System.IO.Path.DirectorySeparatorChar.ToString(), relativeParts);
        return newPath;

    }
我希望列表b也存储它们相对于输入字段中指定的路径的路径。。例如,列表A中的最后三个条目位于名为“undermappe”的子目录中,但由于我使用Path.GetFileName将条目存储在列表B中,因此无法查看子目录。。我该怎么做

只需删除输入字段中的前X个字符,其中X是路径的长度。这可以通过Substring()完成;比如:

string relativePath = stringFromListBox.Substring(stringFromInputField.Length + 1);

“+1”应该去掉前导斜杠。

对于问题的第二部分,关于组合框中的路径,您可以获取每个完整文件名,并使用Path.GetDirectoryName()仅获取目录

var files = new []{@"f:\Noter\Test\2004 ABC Musik.txt",@"f:\Noter\Test\activision_support.txt",@"f:\Noter\Test\Alberte.txt",@"F:\Noter\Test\undermappe\steam password!.txt"};

var folders = files.Select(f => System.IO.Path.GetDirectoryName(f)).Distinct().ToList();

如果只需要主
'F:\noter\test'
文件夹下的文件夹,则只需使用问题第一部分答案中的相对路径代码即可

用于生成ListA和ListB的代码在哪里?我担心,发布图片并不能为我们提供任何代码。我们需要查看代码。我添加了列出“文件”的代码。我得到了最有用的代码。但我的问题是,我还想列出子目录。简言之,我也可以通过从relativePath字符串中删除文件名来使用substring,但是当它应该从右侧而不是左侧执行时,我该如何执行此操作?您能给出一个输入和输出的具体示例吗?这将只从输入框中删除“基本路径”,而只保留任何子目录和文件名。这不是你想要的吗?
             **Hi.
             try this example , i think this is what you need , 100% working:**


             System.String basefolder = "NASSIM\\LOUCHANI\\";

             foreach (String file in Directory.GetFiles(basefolder,"*.*"))
             {
                 comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
                 //Load file name without extension / path.
             }
             **Hi.
             try this example , i think this is what you need , 100% working:**


             System.String basefolder = "NASSIM\\LOUCHANI\\";

             foreach (String file in Directory.GetFiles(basefolder,"*.*"))
             {
                 comboBox1.Items.Add(Path.GetFileNameWithoutExtension(file));
                 //Load file name without extension / path.
             }