9

プロジェクトのフォルダーにある XML ファイルを読み込もうとしています (Visual Studio 2012 を使用)。

構造は次のとおりです。

solutionRoot\
-  service\
--   ServiceClass.cs
--   AppValues.xml  <-- this is the file I want to load

私の ServiceClass では、次のコードを使用して XML ファイルから読み取ろうとしています。

public String GetXmlElement(String elementName)
{
    [....]
    XDocument document = XDocument.Load(@"\service\AppValues.xml");
    [...]
}

コードをテストしようとすると、次のエラーが発生します。

Test method PandaTests.ServiceTest.ReadXmlCanReadXml threw exception: 
System.IO.DirectoryNotFoundException: Could not find a part of the path 
'C:\Users\MyName\Documents\GitHub\project\Project22\PandaTests\bin\Debug\service\AppValues.xml'.

明らかにパスの問題ですが、相対パスを正しく取得する方法がわかりません。ここでスタックオーバーフローに関する他の質問を見てきましたが、それらの多くは過度に複雑に見えます。絶対パスを指定せずに XML ファイルをロードする簡単な方法はありますか?

4

7 に答える 7

4

私は同じ問題に直面し、「Server.MapPath」を使用して解決しました

例えば、

string path=Server.MapPath("~/service/AppValues.xml");

XDocument document = XDocument.Load(path);

それが役に立てば幸い。

于 2015-02-26T10:11:43.063 に答える