c# - 在wpf应用程序的根目录中查找文件

标签 c# xml wpf visual-studio relative-path

我正在尝试使用 pack://application 加载文件:该文件位于我的项目的根目录中,但我不断收到空引用错误。但是,当我进行绝对引用时,它会找到文件并加载得很好。 我在这里缺少什么?

这不起作用

var txt = Application.GetContentStream(new Uri(@"pack://application:,,,/Layout.xml"));
string full = new StreamReader(txt.Stream).ReadToEnd();

或 Pack://Application,,,/的任何变体

这可行,但我不想使用它,而且无论如何似乎都是不好的做法

var path = AppDomain.CurrentDomain.BaseDirectory.Substring(0, (AppDomain.CurrentDomain.BaseDirectory.Length - 10));
var txt = path + @"Layout.xml";
string full = new StreamReader(txt).ReadToEnd();

最佳答案

首先,确保在编译时将文件明确复制到输出 ./bin/ 目录中:

enter image description here

这在我的 WPF 应用程序中非常适合我:

const string imagePath = @"pack://application:,,,/Test.txt";
StreamResourceInfo imageInfo = Application.GetResourceStream(new Uri(imagePath));
byte[] imageBytes = ReadFully(imageInfo.Stream);

如果您想将其读取为二进制文件(例如读取图像文件),则需要此辅助函数。您可能不需要这个,因为您正在读取 .xml 文件。

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16 * 1024];
    using (MemoryStream ms = new MemoryStream())
    {
        int read;
        while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            ms.Write(buffer, 0, read);
        }
        return ms.ToArray();
    }
}

有关更多信息,请参阅Microsoft on Pack URIs in WPF .

关于c# - 在wpf应用程序的根目录中查找文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30996982/

相关文章:

c# 相当于 java.util.concurrent.Future<T>

c# - 如何在编译期间关闭 XSD 中的包含?

wpf - 如何将一组点绘制为单独的圆圈?

c# - 传递继承类

c# - 生成高斯数

c# - 在 .Net Windows 应用程序中缓存

java - "ScrollView can only host 1 child"在 2 个 fragment 中,只有 1 个 child ?

java - 在 TextView 的背景中,在 fragment 中的每个图像上绘制圆圈

c# - Visual Studio 2010 认为它处于 Debug模式(但它设置为 Release模式)

.net - WPF:在具有关闭按钮的子窗口镶边中包含控件