【问题标题】:Path of XML file in Resources folder to FileStream in C# WPF project资源文件夹中的 XML 文件到 C# WPF 项目中 FileStream 的路径
【发布时间】:2014-07-25 12:20:31
【问题描述】:

在一个简单的 WPF 项目中,我有一个 XML 文件“Students.xml”来查看和添加记录。 XML 文件位于项目的 Resources 文件夹中,具有 Build Action : ResourceCopy always 属性。我可以使用以下方式读取 XML:

XDocument doc = XDocument.Parse(Properties.Resources.Students);

但要写入它,FileStream 需要它的字符串路径。

     FileStream fs = new FileStream(Properties.Resources.Students, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
 // exception in first argument, string path should be specified.

那么,我应该如何从 FileStream 中的资源文件夹访问 xml 文件。请帮忙。

【问题讨论】:

    标签: c# xml wpf filestream


    【解决方案1】:

    问题解决了!我刚刚在项目中添加了该文件,并将该文件也复制到了项目的调试文件夹中。现在我可以简单地访问“filename.xml”了。

      XDocument doc = XDocument.Load("Students.xml");
      /...../
     FileStream fs = new FileStream("Students.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    

    现在,它可以工作了。

    【讨论】:

      【解决方案2】:

      如果您使用的是Resource File,则其内容嵌入到程序集中,因此它们没有文件路径。相反,您应该在项目中添加一个名为 Resources 的文件夹,并在其中添加 XML 文件。如果你这样做,那么你可以使用这个属性来访问它:

      public static string ResourceFolderPath
      {
          get
          {
              string path, applicationDirectory = Path.GetDirectoryName(
                  Assembly.GetEntryAssembly().Location);
              if (applicationDirectory.Contains(Environment.GetFolderPath(
                  Environment.SpecialFolder.UserProfile))) path = Path.Combine(
                  applicationDirectory, "Resources");
              else path = Path.Combine(Directory.GetParent(applicationDirectory).Parent.
                  FullName, "Resources");
              return path;
          }
      }
      

      【讨论】:

      • 想对选民发表评论吗?否则,否决投票毫无意义。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-02
      • 2014-07-12
      • 2011-05-25
      • 2020-10-31
      相关资源
      最近更新 更多