System.IO FileNotFound exception while loading XML file.

huangapple go评论67阅读模式
英文:

System.IO FileNotFound exception while loading XML file

问题

FileA 和 FileB 位于同一文件夹。FileB 是一个 XML 文件。

如下所示,从 FileA 中加载 FileB,我遇到了 System.IO FileNotFound 异常。

FileA.cs:

public class FileA 
{     
    private XmlDocument Doc;

    public FileA()
    {             
         var filePath = "FileB.xml"; 
         Doc = new XmlDocument();
         Doc.Load(filePath); // 此行出现异常 - FileNotFound
    }
}

在 Visual Studio 中的项目结构:

  • Solution 'Items'
    • Server
      • bin
        • debug
          • net7.0 -> 此文件夹中有 exe 文件。
            • MyFiles -> FileB.xml 文件被复制到此文件夹
    • Client
      • wwwroot
      • MyFiles
        • FileA
        • FileB
    • Shared

我可以知道我做错了什么。

当前更新的文件路径:

var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../MyFiles", "FileB.xml");
英文:

FileA and FileB are in the same folder. FileB is an XML file.

LoadingFileB from FileA as below. I get System.IO FileNotFound exception.

FileA.cs:

public class FileA 
{     
    private XmlDocument Doc;

    public FileA()
    {             
         var filePath= "FileB.xml"; 
         Doc = new XmlDocument();
         Doc.Load(filePath); // Exception in this line - FileNotFound
    }
}

Project Structure in VS:

-Solution'Items'
   -Server
       - bin
           - debug 
               - net7.0 -> this folder has exe file.
                   - MyFiles -> FileB.xml file is copied in this folder
   -Client
       -wwwroot
       -MyFiles
            -FileA
            -FileB
   -Shared

May I know where I am going wrong.

Current updated filepath:

var filepath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "../../../../MyFiles",
"FileB.xml");

答案1

得分: 2

A class file (FileA.cs) doesn't live in a directory (barring App_Code but don't even think about that), it gets compiled into an assembly which resides in your bin directory. Pass the appropriate relative path accordingly.

So something like:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"../MyFiles",
"FileB.xml");

Also make sure the XML file actually gets copied to the output directory.

英文:

A class file (FileA.cs) doesn't live in a directory (barring App_Code but don't even think about that), it gets compiled into an assembly which resides in your bin directory. Pass the appropriate relative path accordingly.

So something like:

Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
"../MyFiles",
"FileB.xml");

Also make sure the XML file actually gets copied to the output directory.

huangapple
  • 本文由 发表于 2023年3月15日 20:31:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75744733.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定