简体   繁体   中英

How to File.AppendAllText create subdirectory if doesn't exist?

In c# how File.AppendAllText can create subdirectory if doesn't exist and i try this but it not working

File.AppendAllText("\\Logs\\date.txt", "Hi");

You should check if the directory exists, and create it if it does not, like this:

string filename = "\\Logs\\date.txt";
string directoryName = Path.GetDirectoryName(filename);
if (!Directory.Exists(directoryName)) 
{
    Directory.CreateDirectory(directoryName);
}
File.AppendAllText(filename, "Hi");

Directory.CreateDirectory creates all directories and sub-directories, unless they already exist. This means you do not actually need to call Directory.Exists first, but that is my preference.

You need to create the directory ahead of time.

See. Directory.CreateDirectory

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