Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FileStream and creating folders

Tags:

c#

filestream

Just a quick question. I'm using something like this

FileStream fs = new FileStream(fileName, FileMode.Create); 

I was wondering whether there was a parameter I could pass to it to force it to create the folder if it doesn't exist. At the moment an exception is throw if folder isn't found.

If there is a better method then using FileStream I'm open to ideas.

like image 951
Ash Burlaczenko Avatar asked Sep 12 '10 14:09

Ash Burlaczenko


People also ask

What is the use of FileStream?

Remarks. Use the FileStream class to read from, write to, open, and close files on a file system, and to manipulate other file-related operating system handles, including pipes, standard input, and standard output.

How do you create a directory in C?

This task can be accomplished by using the mkdir() function. Directories are created with this function. (There is also a shell command mkdir which does the same thing). The mkdir() function creates a new, empty directory with name filename.

How does FileStream work C#?

The FileStream is a class used for reading and writing files in C#. It is part of the System.IO namespace. To manipulate files using FileStream, you need to create an object of FileStream class. This object has four parameters; the Name of the File, FileMode, FileAccess, and FileShare.


1 Answers

Use Directory.CreateDirectory:

Directory.CreateDirectory Method (String)

Creates all directories and subdirectories as specified by path.

Example:

string fileName = @"C:\Users\SomeUser\My Documents\Foo\Bar\Baz\text1.txt";  Directory.CreateDirectory(Path.GetDirectoryName(fileName));  using (FileStream fs = new FileStream(fileName, FileMode.Create)) {     // ... } 

(Path.GetDirectoryName returns the directory part of the file name.)

like image 186
dtb Avatar answered Sep 19 '22 01:09

dtb