Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Directory not found exception

Tags:

c#

I am trying to write an error log which will store down all errors into a .txt file. But right now, the problem im facing is "Directory Not Found Exception"

Below is my code for my common method (writelog)

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
using System.Diagnostics;

/// <summary>
/// Summary description for Writelog
/// </summary>
/// <param name="ErrorDesc">Desc</param>
/// <param name="ID">ID</param>
/// <param name="ProgPage">Name</param>
/// <param name="Message">Error Message</param>
public class Writelog
{
    public static void WritelogDesc(string Desc, string ID, string Name, string ErrorMessage)
    {
        StringBuilder sBuilder = new StringBuilder();

    string Errorlog = System.Configuration.ConfigurationManager.AppSettings["Errorlog"];

    string path = System.AppDomain.CurrentDomain.BaseDirectory.ToString();

    sBuilder.Append(DateTime.Now.ToString("dd/MM/yyyy") + " " + DateTime.Now.ToShortTimeString());
    sBuilder.Append(" | ");
    sBuilder.Append(Desc);
    sBuilder.Append(" | ");
    sBuilder.Append(ID);
    sBuilder.Append(" | ");
    sBuilder.Append(Name);
    sBuilder.Append(" | ");
    sBuilder.Append(ErrorMessage);

    StreamWriter sw = (!File.Exists(path)) ? File.CreateText(path) : File.AppendText(path);
    sw.WriteLine(sBuilder.ToString());
}

}

And here is how i call the writelog.

 Writelog.WritelogDesc("Desc", "ID", "Name", "ErrorMessage");
like image 885
Nana Avatar asked Oct 28 '09 02:10

Nana


1 Answers

It's not quite clear how you are trying to use the 'path' and 'Errorlog' variables. It looks like you are trying to create a file using the directory path.

You'll need to ensure that the base path for your log file exists before you create the file. Is this close to what you are looking for?

Directory.CreateDirectory(path);
String logfile = Path.Combine(path, Errorlog);
StreamWriter sw = new StreamWriter(logfile, true);
like image 131
jheddings Avatar answered Sep 19 '22 10:09

jheddings