【问题标题】:How to open a WPF Content Stream?如何打开 WPF 内容流?
【发布时间】:2024-04-14 14:40:02
【问题描述】:

这里是代码sn-p

String str= ??????? // I want to assign c:/my/test.html to this string
Uri uri= new Uri (str);
Stream src = Application.GetContentStream(uri).Stream;

这样做的正确方法是什么?我收到“URI 不是相对的”异常抛出

【问题讨论】:

    标签: c# wpf stream uri


    【解决方案1】:

    您的问题是 WPF 特有的。请参阅Application.GetContentStream 方法。

    您将了解到此方法需要一个相对 URI。见“WPF Application, Resource, Content and Data files”。

    【讨论】:

      【解决方案2】:

      您有一个文件路径 - 如果您想将其设为 URI,请添加“file:///”,即。 "file:///c:/my/test.html"

      【讨论】:

      • 谢谢。但是,我得到一个“URI不是相对的”异常
      【解决方案3】:

      对于本地文件 URI,您需要为其添加前缀:

      file:///
      

      【讨论】:

        【解决方案4】:

        我想你会发现你的问题是Application.GetContentStream 是针对位于指定 Uri 的 content 数据文件的资源流。也就是说,与可执行程序集一起部署。

        如果你看:http://msdn.microsoft.com/en-us/library/aa970494(VS.90).aspx#Site_of_Origin_Files

        您应该会发现上述 file:/// 语法是正确的...但是如果您要打开它们,您可能需要某种开关来确定如何获取流:

        FileInfo fileToSave;
        if (!existingFile.IsFile)
            throw new ArgumentException("Input URI must represent a local file path", "existingFile");
        
        fileToSave = new FileInfo(existingFile.LocalPath);
        return fileToSave.Open(/* Args based on your needs */)
        

        同样,如果它是一个网络 URI:

        if (!existingFile.Scheme.StartsWith("http"))
            throw new ArgumentException("Input URI must represent a remote URL path", "existingFile");
        // Do a WebRequest.Create call and attempt download... (Perhaps to MemoryStream for future use)
        

        希望对您有所帮助。

        安德鲁。

        【讨论】:

        • 谢谢。现在我有一个 COM 噩梦(做一个简单的任务太多的管道)。让我进一步支持我正在寻找的内容。我正在编写一个将 .chm 文件转换为适合 Amazon kindle DX 的 .pdf 文件的工具。为此,我需要一个简单的浏览器控件来加载 .html 文件(由 chmdecompiler 解压缩)以查看它是否适合 6 X 8 大小(大多数 .html 动态适合大小,除了带有
           标签或带有大图像的那些)。