【问题标题】:GetFiles() error with user input path用户输入路径的 GetFiles() 错误
【发布时间】:2017-09-24 12:32:24
【问题描述】:

我正在尝试从控制台中的用户输入获得的路径获取目录中的所有文件。但我不断收到此错误“System.ArgumentException: 'Second path fragment must not be a drive or UNC name' 我看过这个 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,但看不到。有任何想法吗?提前致谢

【问题讨论】:

  • 您试图在第二个 sn-p 中提供指向 GetFiles 的路径,这会导致问题。你在第一个中没有它。删除该参数。
  • @SamiKuhmonen 非常感谢您指出这一点。我已经在这里坐了大约一个小时试图弄清楚。一双新鲜的眼睛总是有帮助的。谢谢你纠正我的白痴

标签: c#


【解决方案1】:

简单示例:

    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();
    }

【讨论】:

  • 我知道我发帖太晚了!等我到50了,我就可以给别人的帖子加cmet了!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-05
  • 1970-01-01
  • 2013-03-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多