当我清楚地调用这个单例并且它应该调用Logger()来设置filename变量时,我无法弄清楚为什么我一直在文件名上获得null ref:
public class Logger
{
private static Logger defaultLogger = null;
readonly string filename;
public static Logger DefaultLogger
{
get
{
// Check for valid instance
if (defaultLogger == null)
defaultLogger = new Logger();
// Return instance
return defaultLogger;
}
}
private Logger()
{
filename = ConfigurationManager.AppSettings["MyLogPath"];
}
public string Filename
{
get { return this.filename; }
}
public void Write(EntryType type, string data)
{
lock (this)
{
using (StreamWriter writer = new StreamWriter(filename, true))
{
//do something
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我打电话给这个班级的方式:
Logger.DefaultLogger.Write(EntryType.Error, e.ToString());
Run Code Online (Sandbox Code Playgroud)
所以我在运行时说文件名为null时得到这个错误:
Value cannot be null.
Parameter name: path
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: path
Source Error:
Line 49:
Line 50:
Line 51: public string Filename
Line 52: {
Line 53: get { return this.filename; }
Run Code Online (Sandbox Code Playgroud)
这是我们的原始代码(我没有写这个),同样的问题:
public class Logger
{
public static Logger DefaultLogger = new Logger();
string filename;
public Logger()
{
filename = ConfigurationManager.AppSettings["LogPath"];
}
public Logger(string filename)
{
this.filename = filename;
}
public string Filename
{
get { return this.filename; }
}
public void Write(LogEntryType type, string data)
{
lock ()
{
using (StreamWriter writer = new StreamWriter(filename, true))
{
...
}
}
}
Run Code Online (Sandbox Code Playgroud)
是因为
ConfigurationManager.AppSettings["MyLogPath"];
Run Code Online (Sandbox Code Playgroud)
一片空白?
检查您的App.Config文件是否存在(它采用yourexe.exe.configbin文件夹中的形式).你App.Config应该有以下几行:
<configuration>
<appSettings>
<add key="MyLogPath" value="C:\Simple.txt" />
<appSettings>
</configuration>
Run Code Online (Sandbox Code Playgroud)
也许为了测试,你可以临时将文件名设置为一个众所周知的路径( filename=@"D:\C#\mytext.txt";),看看你是否得到错误.
如果我明确设置文件名,那么如果我设置,我就不会有这样的错误OTOH
filename=ConfigurationManager.AppSettings["MyLogPath"];
Run Code Online (Sandbox Code Playgroud)
然后我会得到一个
System.ArgumentNullException:值不能为null.参数名称:System.IO.StreamWriter..ctor处的路径(String path,Boolean append,Encoding encoding,Int32 bufferSize)System.IO.StreamWriter..ctor(String path,Boolean append)
如果我使用调试器,我可以看到它失败了:
(StreamWriter writer = new StreamWriter(filename, true))
Run Code Online (Sandbox Code Playgroud)
我不知道为什么你的调试器不会命中构造函数.在这两种情况下,我的调试器都击中了构造函数.
| 归档时间: |
|
| 查看次数: |
2550 次 |
| 最近记录: |