2

I'm creating a logger for my app and I'm stuck with a problem I need to save my log file in my C drive but when I'm executing the Code its give me an error "Given Path Format Is Not Supported" My current code is given below

string path="C:\\Logger\\"+DateTime.Now.Date.ToString()+".txt";

    public void CreateDirectory()
    {
        if(!File.Exists(path))
        {
            File.Create(path);
        }
    }

any solutions????

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
Optimus
  • 2,200
  • 8
  • 37
  • 71
  • What Adel said is probably the key to finding the issue here. In general, if you encounter something like this, it would be helpful if you added the actual content of the variables. Have you tried debugging your code? – Sebastiaan van den Broek Jul 27 '13 at 09:45
  • you can leave it to a framework such as Enterprise Library. http://stackoverflow.com/questions/1260157/whats-the-most-widely-used-logging-framework-in-c) – yavuz Jul 27 '13 at 11:14

2 Answers2

6

You're going to have to format the date:

string path="C:\\Logger\\"+DateTime.Now.Date.ToString("yyyy_MM_dd")+".txt";

because the operating system isn't going to accept something like this:

C:\Logger\07/27/2013.txt

Now, for future reference, consider using Path.Combine to build your paths:

var path = Path.Combine("C:\\Logger",
    DateTime.Now.Date.ToString("yyyy_MM_dd"),
    ".txt");

You won't have to determine when to provide back slashes and when not to. If there isn't one, it will be appended for you.

Finally, you may experience problems if the directory doesn't exist. Something you can do to mitigate that is this:

var path = ...
var dir = Path.GetDirectoryName(path);

if (!Directory.Exists(dir))
{
    Directory.Create(dir);
}

But even then, you can run into permissions issues during runtime.

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
1

Check that the result of this: DateTime.Now.Date.ToString() is accepted by the operating system.

Adel Khayata
  • 2,717
  • 10
  • 28
  • 46