Create a Folder - Newbie Question

M

Miro

Again, not looking to waste a lot of time here... its a simple question, the
code works, but wanted to get some simple opinions.

I have this: ( to create a "data" folder )
Imports System.IO 'Required for DirectoryInfo

-and then in a function...
Dim FolderInfo As DirectoryInfo = New DirectoryInfo("Data")
If Not System.IO.Directory.Exists(FolderInfo.ToString) Then
FolderInfo.Create()
End If

'Continue code here


Is that correct to create a "FolderInfo" variable and then use the
System.IO.Directory.Exist on it to create it?
-Is it correct to FolderInfo.ToString it ? Or should I create a "Dim
Folder As String = "Data" and use that there instead?

One last question...
How would I know to add an Imports line ? is there something I should
always look for to know Im missing one?


Thanks,

Miro
 
C

Chris Dunaway

Miro said:
Is that correct to create a "FolderInfo" variable and then use the
System.IO.Directory.Exist on it to create it?
-Is it correct to FolderInfo.ToString it ? Or should I create a "Dim
Folder As String = "Data" and use that there instead?

You can just use the Directory class without instantiating anything:

If Not Directory.Exists("Data") Then
Directory.CreateDirectory("Data");
End If

As far as creating a string for the foldername is concerned, do that if
you will use the folder name later in the code besides just creating
the folder.
How would I know to add an Imports line ? is there something I should
always look for to know Im missing one?

By just being familiar with the classes you are using will tell you if
you need an Imports line. Strictly speaking, you don't need them at
all, they are just conveniences to help shorten your code.
 
M

Miro

Thank you,

Thats the answer I was looking for.

To think in my Searching of all the different ways to see if a folder
exists,
I would have found Directory.Exists

Miro
 
G

GhostInAK

Hello Chris,

In addition to Chris's comments..
You should never ever use relative paths in your code. You should allways
work with full paths. I could easily change the working directory of your
application and then later change it again, and again.. ad infinitum.. If
you don't care where this "Data" directory is.. or care that it will be in
the same location between runs.. by all means use relative paths.

-Boo
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top