Audy
Audy

Reputation: 21

DateTime Not working in Global.asax in c#

I am trying to use DateTime in global.asax to give a name to a file but it gives an error. Could you please assist?

The code I am using for the DateTime;

public void callFileCreate()
{
    string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();


    string filename = HttpContext.Current.Server.MapPath(path + "\\Log_" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
    TraceFilePath = HttpContext.Current.Server.MapPath(path + "\\Scheduler" + DateTime.Now.ToShortDateString().Replace("/", ".") + "_" + (DateTime.Now.ToLongTimeString()).Replace(":", "_") + ".txt");
    FileStream fs = null, fs1 = null;
    fs = File.Create(filename);
    fs1 = File.Create(TraceFilePath);
    ErrorFilePath = filename;
}

Upvotes: 0

Views: 531

Answers (2)

Tim Schmelter
Tim Schmelter

Reputation: 460340

You should use the Path class if you work with paths:

string path = ConfigurationManager.AppSettings["LogFileFolder"].ToString();
string fileName = string.Format("{0}_{1}_{2}.txt"
    , "Log"
    , DateTime.Today.ToString("dd.MM.yyyy")  // change according to your actual culture
    , DateTime.Now.ToString("HH_mm_ss"));
string fullPath = Path.Combine(path, fileName);

Not sure if that solves your issue, but it increases readability and avoids careless mistakes anyway.

Upvotes: 1

M4N
M4N

Reputation: 96626

You don't write what error you get. But here are some hints about how you can simplify your code:

var dir = HttpContext.Current.Server.MapPath(
              ConfigurationManager.AppSettings["LogFileFolder"].ToString());
var dt = DateTime.Now.ToString("yyyy.MM.dd_HH.mm.ss");

var logFilePath = Path.Combine(dir, string.Format("Log_{0}.txt", dt));
var traceFilePath = Path.Combine(dir, string.Format("Scheduler_{0}.txt", dt));

var fs = File.Create(logFilePath);
var fs1 = File.Create(traceFilePath);

Notes:

  • if the app-settings entry LogFileFolder already contains an (absolute) filesystem-path such as c:\temp, then you shouldn't call Server.MapPath().
  • you should call fs.Close() once you no longer need the streams (or put it in a using block). Otherwise, another attempt to create the (same) file will result in an exception.

Upvotes: 0

Related Questions