[API Proposal]: Add an option to create parent directories in System.IO.File
APIs
#110919
Labels
api-suggestion
Early API idea and discussion, it is NOT ready for implementation
area-System.IO
untriaged
New issue has not been triaged by the area owner
Background and motivation
I find it a common task to create (then subsequently write into) a file, given a complete path to be saved.
For example, when given a list of relative paths to files, I might want to save all the files while preserving the directory hierarchy, which might look like this:
The APIs under the
System.IO.File
class is usually good enough for quick and dirty codes that involve simple read/write/creations of files (e.g., scripting)However, one needs to make sure that all of the parent directories exist, otherwise they get hit with a
DirectoryNotFoundException
in the face when part of the directories are missing:Popular workaround this involves the use of
FileInfo
, accessing itsDirectory
property to callCreate
which ensures that all the subdirectories leading to the file exists (and does nothing if they already exist)(See https://stackoverflow.com/questions/2955402/how-do-i-create-directory-if-it-doesnt-exist-to-create-a-file)
But to me this feels weird because I'm creating a
FileInfo
and aDirectoryInfo
object which then I immediately throw away.An alternative would be to create the directory without the
FileInfo
, which is also suggested in the above StackOverflow post:Looking at libraries from different languages / frameworks, Node.js seems to have a popular file system library,
fs-extra
, that has a method calledoutputFile
which creates the parent directory if it does not exist.I feel like I'm running into this problem quite frequently in a lot of different places; Often when a file creation fails because of missing directories I just want it to create one. It sure would be nice if there is a way to make these methods create parent directories if it does not exist...
API Proposal
Any method that involves creation of a file are included in the list.
Open questions
Open
methods get included in this? Depending on theFileMode
it may not end up creating a new file.OpenHandle
be included in this? The use of file handles IMO falls into more of an advanced API.CreateSymbolicLink
?Copy
/Move
/Replace
?createDirectories
(singularcreateDirectory
?)API Usage
Alternative Designs
None from what I can think of currently...
Risks
The text was updated successfully, but these errors were encountered: