英文:
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 文件被复制到此文件夹
 
 
 - net7.0 -> 此文件夹中有 exe 文件。
 
 - debug
 
 - bin
 - Client
- wwwroot
 - MyFiles
- FileA
 - FileB
 
 
 - Shared
 
 - Server
 
我可以知道我做错了什么。
当前更新的文件路径:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论