Search code examples
c#asp.netentity-frameworkiis-7.5

How to create Directory/File into IIS using ASP.NET C# Entity Framework


My work environment is:

  • Windows 7 Professional
  • Visual Studio 2019, ASP.NET MVC, Entity Framework
  • SQL Server Express
  • IIS Version 7.5 (installed locally)

When I debug in Visual Studio, the directory/file is created without problem inside this path ~/Content/Documentacion/log/ (using IIS Express that comes with VS).

But when I publish the solution and run it using IIS 7.5, the directory/file is not created, I cannot understand the problem.

This is the code:

public void CreaLogATiempos(DateTime fin, bool sobrescribir = false)
{
    try
    {
        text = "xxxxx= ";
        string docPath = "~/Content/Documentacion/log/" ;
        var folder = System.Web.HttpContext.Current.Server.MapPath(docPath );

        if (!Directory.Exists(folder))
        {
            Directory.CreateDirectory(folder);
        }

        FileInfo MyFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath(docPath + this.archivo));

        if (!MyFile.Exists)
        {
            StreamWriter crear = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath(docPath + this.archivo));
            crear.WriteLine(text);
            crear.Close();
        }
        else
        {
            StreamWriter crear = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath(docPath + this.archivo), true);
            crear.WriteLine(text);
            crear.Close();
        }
    }
    catch (Exception e)
    {
        Console.WriteLine("Exception: " + e.Message);
    }
}

Maybe someone can see the error or has an idea about the problem?


Solution

  • Can I introduce you to TextWriterTraceListener? Add this to your Global.vb file:

    'adding tracing to a log.
    Trace.Listeners.Clear()
    
    Dim stream As New IO.FileStream(Server.MapPath("~/App_Data/trace.log"), IO.FileMode.Append)
    Dim writer As New IO.StreamWriter(stream, System.Text.Encoding.UTF8)
    
    Dim logListener As New TextWriterTraceListener(writer, "trace.log")
    Trace.Listeners.Add(logListener)
    Trace.AutoFlush = True
    
    Trace.WriteLine($"{DateTime.Now.ToString} - class: Global.asax - method: Application_Start - message: Trace listener loaded.")
    

    Create a trace.log file inside "~/App_Data"