代码之家  ›  专栏  ›  技术社区  ›  Markus

C为什么我的文件路径上出现不支持的异常

  •  1
  • Markus  · 技术社区  · 16 年前
    StreamReader fr = new StreamReader("D:\\test\\" + item);
    

    这就是我想做的。项是具有文件名的字符串。孔弦就是这样的

    "D:\\test\\01-Marriotts Island.mp3"
    

    在他尝试生成streamreader之前。 这条路怎么了?

    3 回复  |  直到 16 年前
        1
  •  8
  •   Amal Sirisena    16 年前

    streamreader是为读取字符数据而设计的。你应该使用 BinaryReader 相反,如果您试图读取二进制数据,例如MP3文件的内容。

    更新:正如马克指出的,你也可以使用 Stream 要读取文件,这可能提供比BinaryReader更易于使用的界面来操作文件。另外,我赞同他的建议 Path.Combine 在建立要访问的文件的路径时。

        2
  •  4
  •   Marc Gravell    16 年前

    还有其他的信息吗?有关信息,组合路径的最简单方法是 Path.Combine :

    using(StreamReader fr = new StreamReader(Path.Combine(@"D:\Test", item))) {
       // ...
    }
    

    (也注意 using 以确保其被处置)

    或更清晰(IMO):

    using(StreamReader fr = File.OpenText(Path.Combine(@"D:\Test", item))) {
        // ...
    }
    

    (当然,正如其他地方提到的,a StreamReader 可能不适合MP3)

        3
  •  2
  •   bobbymcr    16 年前

    咨询 MSDN documentation for StreamReader 我看不见 NotSupportedException 列为此API将引发的异常。然而, another similar constructor overload 列出它:

    冒号 路径包括 的语法不正确或无效 文件名、目录名或卷 标签。

    所以我自己用了一个无效的音量标签,确实 冒号 :

    StreamReader reader = new StreamReader("DD:\\file.txt");
    
    // throws...
    //
    // Unhandled Exception: System.NotSupportedException: The given path's format is not supported.
    

    所以我猜你的路有问题。