创建日志事件文件在Windows服务在C#
问题描述:
我想知道如何通过C#创建在窗口服务日志事件文件的新目录的新目录创建日志事件文件在Windows服务在C#
我有以下代码:
public static void WriteLog(string Message)
{
StreamWriter sw = null;
try
{
sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true);
//sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true);
//sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
sw.WriteLine(Message);
sw.Flush();
sw.Close();
}
catch{}
}
答
File yourFolder= new File("C:/yourFolder");
// if the directory does not exist, create it
if (!yourFolder.exists()) {
System.out.println("Creando directorio: " + yourFolder.getName());
boolean result = false;
try
{
yourFolder.mkdir();
result = true;
}
catch(SecurityException se){
}
if(result) {
System.out.println("Folder created");
}
}
答
对于Directory.CreateDirectory(path)
的docuemtation状态:
科瑞除非它们已经存在,否则指定指定路径中的所有目录和子目录。从example source code修改
:
string path = @"c:\MyDir";
try
{
// Try to create the directory.
Directory.CreateDirectory(path);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
有上dotnetperls一个真正伟大的教程包含示例代码,异常,提示和其他有用的信息有关创建目录!
查找that SO-question创建相同的目录文件夹内的可执行文件已经开始,或简单的使用relative paths instead of absolute ones:
Directory.CreateDirectory("Test");
这样,你将永远不会有关于寻找正确的路径冲突!
希望你应该阅读这个http://stackoverflow.com/help/how-to-ask –