C# 未找到目录异常
我正在尝试写一个错误日志,它会将所有错误存储到一个.txt文件中。 但现在,我面临的问题是“目录未找到异常” 下面是我常用方法(writelog)的代码C# 未找到目录异常,c#,C#,我正在尝试写一个错误日志,它会将所有错误存储到一个.txt文件中。 但现在,我面临的问题是“目录未找到异常” 下面是我常用方法(writelog)的代码 您的path是一个目录(string path=System.AppDomain.CurrentDomain.BaseDirectory.ToString()),但您将其用作文件(File.Exists(path)) 也许您应该将路径定义为如下内容: string path = Path.Combine(System.AppDomain.Cur
您的
path
是一个目录(string path=System.AppDomain.CurrentDomain.BaseDirectory.ToString()
),但您将其用作文件(File.Exists(path)
)
也许您应该将路径定义为如下内容:
string path = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Errorlog)
如果Errorlog
是您的文件名(例如,“xys.txt”)构建文件路径:
string Errorlog=System.Configuration.ConfigurationManager.AppSettings["Errorlog"];
string path = System.AppDomain.CurrentDomain.BaseDirectory + Errorlog;
.......
.......
StreamWriter sw = (!File.Exists(path)) ?
File.CreateText(path) : File.AppendText(path);
sw.WriteLine(sBuilder.ToString());
不太清楚您是如何使用“path”和“Errorlog”变量的。看起来您正在尝试使用目录路径创建文件
在创建日志文件之前,需要确保日志文件的基本路径存在。这接近你要找的吗
Directory.CreateDirectory(path);
String logfile = Path.Combine(path, Errorlog);
StreamWriter sw = new StreamWriter(logfile, true);
您可以使用filemon()检查fil系统上实际发生的情况
通过这种方式,您可以看到程序何时尝试获取文件系统的句柄以及程序需要的文件和目录。请调试/检查实际使用的路径。您将很快看到生成异常的原因。
string Errorlog=System.Configuration.ConfigurationManager.AppSettings["Errorlog"];
string path = System.AppDomain.CurrentDomain.BaseDirectory + Errorlog;
.......
.......
StreamWriter sw = (!File.Exists(path)) ?
File.CreateText(path) : File.AppendText(path);
sw.WriteLine(sBuilder.ToString());
Directory.CreateDirectory(path);
String logfile = Path.Combine(path, Errorlog);
StreamWriter sw = new StreamWriter(logfile, true);