0

I am wondering on how to create a new directory for a log event file in windows service through c#

I have the following code:

public static void WriteLog(string Message)
{
    StreamWriter sw = null;
    try
    {
        sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "\\DataFile.txt", true);
        //sw = new StreamWriter(AppDomain.CurrentDomain.BaseDirectory + "C:\\MulpuriServiceLOG\\data.txt", true);

        //sw.WriteLine(DateTime.Now.ToString() + ": " + Message);
        sw.WriteLine(Message);
        sw.Flush();
        sw.Close();
    }
    catch{}
}
TheRealVira
  • 1,444
  • 4
  • 16
  • 28

2 Answers2

1

As the docuemtation states for the Directory.CreateDirectory(path):

Creates all directories and subdirectories in the specified path unless they already exist.

Modified from the example source code:

string path = @"c:\MyDir";

try 
{
    // Try to create the directory.
    Directory.CreateDirectory(path);
} 
catch (Exception e) 
{
    Console.WriteLine("The process failed: {0}", e.ToString());
} 
finally {}

There is a really great tutorial on dotnetperls containing example code, exceptions, tips and other useful information about creating directories!

Look up that SO-question to create folders inside the same directory your executable has started, or simple use relative paths instead of absolute ones:

Directory.CreateDirectory("Test");

That way you will never have conflicts about finding the correct path!

Community
  • 1
  • 1
TheRealVira
  • 1,444
  • 4
  • 16
  • 28
0
    File yourFolder= new File("C:/yourFolder");

    // if the directory does not exist, create it
    if (!yourFolder.exists()) {
        System.out.println("Creando directorio: " + yourFolder.getName());
        boolean result = false;

        try
        {
            yourFolder.mkdir();
            result = true;
        } 
        catch(SecurityException se){

        }        
        if(result) {    
            System.out.println("Folder created");  
        }
    }