我的代码有什么问题?显示未处理的异常:System.IO.FileNotFoundException



我正在学习 c#,我正在尝试使用带有Factory Method Design PatternThree Tier Architecture进行基本的登录Console Application。我添加了所有层并实现了与登录应用程序关联的所有逻辑。 但是当我尝试使用dotnet run命令运行代码时,它会要求输入,输入后它会给出错误

未处理的异常:System.IO.FileNotFound异常:无法加载 文件或程序集 'DataAccessLogic, 版本=1.0.0.0, 区域性=中性, PublicKeyToken=null'。系统找不到指定的文件。 at BusinessLogic.User.getUserName(( at FactoryMethod.Program.Main(String[] args( in C:\Users\xxx\Desktop\FactoryPatternSample\FactoryMethodSampleApplication\FactoryMethod\Program.cs:line 14

尽管该文件存在于 BusinessLogic.User.getUserName((;

此处提供的代码

伊洛金.cs

public interface ILogin
{
bool AttemptLogin();
string getUserName();
}

用户.cs

using System;
using DataAccessLogic;
namespace BusinessLogic
{
class User:ILogin
{
private string m_username;
private string m_password;
public User(string username, string password)
{
this.m_username = username;
this.m_password = password;
}
public bool AttemptLogin()
{
if(m_username.Equals("abc") && m_password.Equals("abc123"))
{
return true;
}
return false;
}
public string getUserName()
{
IGetDetails objectType = GetDetails.getDetails(m_username);
Console.WriteLine(objectType.getStudentName());
return objectType.getStudentName();
}
}
}

IGetDetails.cs

using System;
namespace DataAccessLogic
{
public interface IGetDetails
{
string getStudentName();
string getStudentId();
}
}

获取详细信息.cs

namespace DataAccessLogic
{
public class GetDetails
{
public static IGetDetails getDetails(string username)
{
Console.WriteLine(username);
IGetDetails objectType = null;
objectType = new GetValue(username);
return objectType;
}
}
}

获取价值.cs

namespace DataAccessLogic
{
public class GetValue:IGetDetails
{
private string m_username = string.Empty;
public GetValue(string username)
{
this.m_username = username;
}
public string getStudentName()
{
return m_username;
}
public string getStudentId()
{
return "2205";
}
}

在程序中.cs

ILogin loginType = Login.attemptLogin(email, password);
if(loginType.AttemptLogin())
{
Console.WriteLine("Name: "+ loginType.getUserName());
}

在loginType.getUserName((中给出错误,如果我将getUserName()方法更改为仅返回一个字符串,例如"hello",它将给出输出,但是当我尝试从对象返回字符串时IGetDetails给出错误。

完整的代码 Github

任何帮助将不胜感激。

提前谢谢。

正如我从您的FactoryMethod.csproj文件中看到的那样,您没有在项目中引用DataAccessLogicFactoryMethod。这就是为什么DataAccessLogic.dll没有复制到bin/Debug/netcoreapp2.0/文件夹中的原因,异常消息实际上告诉您。

您可以手动复制此文件并检查您的应用程序现在是否运行,但这会更好地修复您的引用。

解释:

您引用BusinessLogic作为外部文件依赖项(..BusinessLogicobjDebugnetstandard2.0BusinessLogic.dll(,而不是项目到项目。这样,.Net CLR 就不知道BusinessLogic依赖项,只是将此文件复制到FactoryMethod项目的输出目录中。

然后,在运行时,CLR 将看到,在 14 行Program.cs文件时,它需要一个GetDetails类,该类位于程序集DataAccessLogic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null中。它尝试从工作目录加载此程序集,但没有找到它,因此它抛出System.IO.FileNotFoundException.

溶液:

始终手动复制此文件修复引用,以便FactoryMethod项目将引用BusinessLogic项目(而不是文件(。这可以在窗口中Projects选项卡中Reference Manager完成。

现在,Visual Studio将构建过时的BusinessLogic项目并copy-if-newer其所有依赖项。

此外,以相同的方式修复项目中BusinessLogic引用。 有一个关于参考文献的很好的文档。看一看。

最新更新