0

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;
}
Hexie
  • 3,955
  • 6
  • 32
  • 55
Audy
  • 21
  • 1
  • 9

2 Answers2

1

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.

Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
0

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.
M4N
  • 94,805
  • 45
  • 217
  • 260
  • You don't know OP's culture, so you don't know if it is `yyyy.MM.dd` or `dd.MM.yyyy` or whatelse. – Tim Schmelter Aug 07 '13 at 11:02
  • @Tim: I guess you want to have a consistent (i.e. culture-independent) format for the file names and not depend on the current culture (which might be different for each request/user in a web app). – M4N Aug 07 '13 at 11:04
  • Yes, but OP's original code was culture dependent, not sure if that's desired. – Tim Schmelter Aug 07 '13 at 11:07