I was reading some file IO tutorials for C# and have managed to write out some files, but what if the path I'm given contains directories?
For example, I want to create the file called data/my_file
except data
folder doesn't exist.
The line,
BinaryWriter outFile = new BinaryWriter(File.OpenWrite(path));
where path
is the above string, crashes with the message that part of the path doesn't exist, which means C# isn't creating them as required.
I would like C# to handle all of the messy directory creation and checking for me instead of me having to parse the path and create all of the necessary directories. Is this possible? Otherwise, is there a snippet of code that I can just copy over into my project which will handle anything I might be overlooking (since I don't know much about file management).
While System.IO.Directory.CreateDirectory() will indeed create directories for you recursively, I came across a situation where I had to come up with my own method. Basically System.IO doesn't support paths over 260 characters, which forced me to use Delimon.Win32.IO library, which works with long paths, but doesn't create directories recursively.
Here's the code I used for creating directories recursively:
So, the above didn't work super well for me for basic directory creation. I modified this a bit to handle common cases for drive letters and a path with a file resource on the end.
System.IO.Directory.CreateDirectory() will create all directories and subdirectories in a specified path, should they not already exist.
You can call it, passing the path, to ensure the folder structure is created prior to writing your file.
Previous answers didn't handle Network paths. Attached code which also handles that.
And the "CleanDoubleSlashes function":
here is how I usually do it
^ this should take care of ensuring all necessary folders (regardless if some of them already exist) that precedes your file are created. E.g. if you pass it "c:/a/b/c/data/my file.txt", it should ensure "c:/a/b/c/data" path is created.