用户输入路径

时间:2017-09-24 12:32:25

标签: c#

我正在尝试从控制台中的用户输入获取的路径中获取目录中的所有文件。但我不断收到此错误'System.ArgumentException:'第二个路径片段不能是驱动器或UNC名称'我已经查看了这个Second path fragment must not be a drive or UNC name - Create Subdirectory Error答案,其中说错误是因为路径中的驱动器名称,但这没有意义。当我像这样测试代码时,当路径被硬编码 WITH 驱动器号时,它就可以工作。

DirectoryInfo d = new DirectoryInfo(@"C:\Users\Christopher Thesner\Desktop\Spoon\");
            dir = d.GetDirectories();
            files = d.GetFiles();

但是当我这样尝试时,路径存储在来自用户输入的变量中,会引发错误。

DirectoryInfo d = new DirectoryInfo(path);
            dir = d.GetDirectories();
            files = d.GetFiles(path);

我试图将字符串中的目录名称作为这样的路径

directory = Path.GetDirectoryName(directory);

正如此处所建议的Second path fragment must not be a drive or UNC name - Create Subdirectory Error但不看。有任何想法吗?提前致谢

1 个答案:

答案 0 :(得分:0)

简单示例:

    private void Form1_Load(object sender, EventArgs e)
    {
        var path = Environment.CurrentDirectory;
        List<String> lines = new List<string>();
        DirectoryInfo d = new DirectoryInfo(path);
        var dir = d.GetDirectories();
        var files = d.GetFiles();
        lines.Add(String.Format("There are {0} directories in \"{1}\"", dir.Length, d.Name));
        lines.Add(String.Format("There are {0} files in \"{1}", files.Length, d.Name));
        foreach (var di in dir)
        {
            lines.Add(String.Format("There are {0} directories in \"{1}\"", dir.Length, d.Name));
            files = di.GetFiles();
            lines.Add(String.Format("There are {0} files in \"{1}", files.Length, d.Name));
        }
        textBox1.Lines = lines.ToArray();
    }