简体   繁体   中英

Create directory if not exists

I want to make logs for differenct actions. I create a new file every day with the date as file name. Now, if the directory doesnt exist, I want the system to make the directory for me. I have searched for this topic and all answers come to the same thing: use Directory.CreateDirectory(FilePath); . However this doesnt seem to work. Might be missing something obvious.

Here's the code:

public class ElderlyHomeLog : ILog
    {
        private const string FilePath = "/Logs/WZCLogs/";
        public void MakeLog(string text)
        {
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
            string logFile = DateTime.Now.ToString("ddMMyyyy") + ".txt";
            if (!File.Exists(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile))
            {
                FileStream f = File.Create(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile);
                f.Close();
            }

            using (StreamWriter sw = new StreamWriter(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile, true))
            {
                sw.WriteLine(text);
                sw.Close();
            }
        }
    }

Error message:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code

Additional information: Could not find a part of the path 'C:\\Users\\***\\Source\\Repos\\Project\\ProjectName\\Logs\\WZCLogs\\31032016.txt'.

The folder may created in your C:\\ ( the default drive where OS is installed). that is folder location is C:\\Logs\\WZCLogs\\ . you can confirm that a folder is created somewhere in the drive-by executing the code again, this time the if (!Directory.Exists(FilePath)) returns true . Since you have not specified any location the compiler assumes So. Check whether it is created or not;

You can extend the try Like this:

try
{
    Directory.CreateDirectory(FilePath);
}
catch (Exception ex)
{
    // handle them here
}

If the path is a wrong one definitely an exception will be thrown; I have tried with "X:\\sample" which gives me the exception:

Could not find a part of the path 'X:\\sample

Whereas if I tried with Logs\\WZCLogs which won't give any exception for the first time and also skip the if for the second time; Hence I found that the folder is created somewhere else;

You can make these changes to make them work:

 string FilePath=Path.Combine(HostingEnvironment.ApplicationPhysicalPath, @"Logs\WZCLogs");

You need to use the absolute path when creating the directory. Try the following:

private const string FilePath = "Logs/WZCLogs/";

public void MakeLog(string text)
{
     string directory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, FilePath);
     Directory.CreateDirectory(directory); // no need to check if it exists

     string logFile = Path.Combine(directory, DateTime.Now.ToString("ddMMyyyy") + ".txt");
     if (!File.Exists(logFile))
     {
         FileStream f = File.Create(logFile);
         f.Close();
     }

     using (StreamWriter sw = new StreamWriter(logFile, true))
     {
         sw.WriteLine(text);
         sw.Close();
     }
}

You do not need to check if the directory exists first as the CreateDirectory method has no side-effects if the directory is already present. It's also good practice to use Path.Combine rather than concatenating strings directly, but make sure the second parameter does not start with a slash.

You could also simplify your code by using the File.AppendAllText method instead of creating a FileStream .

private const string FilePath = "Logs/WZCLogs/";

public void MakeLog(string text)
{
    string directory = Path.Combine(HostingEnvironment.ApplicationPhysicalPath, FilePath);
    Directory.CreateDirectory(directory);

    string logFile = Path.Combine(directory, DateTime.Now.ToString("ddMMyyyy") + ".txt");
    File.AppendAllText(logFile, text + Environment.NewLine);
}

I want to make logs for differenct actions. I create a new file every day with the date as file name. Now, if the directory doesnt exist, I want the system to make the directory for me. I have searched for this topic and all answers come to the same thing: use Directory.CreateDirectory(FilePath); . However this doesnt seem to work. Might be missing something obvious.

Here's the code:

public class ElderlyHomeLog : ILog
    {
        private const string FilePath = "/Logs/WZCLogs/";
        public void MakeLog(string text)
        {
            if (!Directory.Exists(FilePath))
            {
                Directory.CreateDirectory(FilePath);
            }
            string logFile = DateTime.Now.ToString("ddMMyyyy") + ".txt";
            if (!File.Exists(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile))
            {
                FileStream f = File.Create(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile);
                f.Close();
            }

            using (StreamWriter sw = new StreamWriter(HostingEnvironment.ApplicationPhysicalPath + FilePath + logFile, true))
            {
                sw.WriteLine(text);
                sw.Close();
            }
        }
    }

Error message:

An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.dll but was not handled in user code

Additional information: Could not find a part of the path 'C:\\Users\\***\\Source\\Repos\\Project\\ProjectName\\Logs\\WZCLogs\\31032016.txt'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM