tags:

views:

30

answers:

2

Hi all!

A newbie question perhaps... :-S

In config of my app I've a path, for example "logs\updater\updater.log" Starting the app, I wanna create the file updater.log, creating all subfolders if they not exists. So, if tomorrow my user changes the path in config to "logs\mypathisbetter\updater.log", my app continues to work, writing log to the new file.

File.Crate, FileInfo.Create, Streamwriter.Create or so: they do that? Or I need to check if folders exists, before? I can't find a clear answer to this question on the net.

Thank you all in advance!

Ciao, Nando

+1  A: 

No, they don't seem to - you'll get a DirectoryNotFoundException, I believe from all three.

You need to do something like a Directory.CreateDirectory(path) first.

EDIT:

For a bit more of a full solution which starts with a path including filename, try:

    Directory.CreateDirectory(Path.GetDirectoryName(fullPath));

    TextWriter writer = new StreamWriter(fullPath);
    writer.WriteLine("hello mum");
    writer.Close();

But bear in mind you'll need some error handling too, so that the writer always gets closed (in a 'finally' block).

Grant Crofton
In fact, I tried too.There's a "Best Practice" to do that work?Some ideas? :-)
Ferdinando Santacroce
I updated my answer, does that help?
Grant Crofton
Solved using a little bit of code: private static void CreateFile(string filePath) { FileInfo fi = new FileInfo(filePath); if (!fi.Directory.Exists) { System.IO.Directory.CreateDirectory(fi.DirectoryName); } }
Ferdinando Santacroce
What to do to paste formatted code?! :-S
Ferdinando Santacroce
Grant Crofton
Thank you Grant!
Ferdinando Santacroce
A: 

Solved using a little bit of code:

private static void CreateFile(string filePath) 
{ 
  FileInfo fi = new FileInfo(filePath);
  if (!fi.Directory.Exists) 
  { 
    System.IO.Directory.CreateDirectory(fi.DirectoryName); 
  } 
}

Sorry for this really newbie post... Thank you all! :-)

Ferdinando Santacroce