How to Write to A Directory From Visual Basic, First Making the Directory Path, Then Adding the file Name to a File Writer

I am attempting to write data to a file from a parameter that is stored within a SQL Server 2005 database. (The value of the entire file path can be retrieved by a query similar to "Select EDIOutputPath From SystemParms;.") I need to figure out how to first take the value returned by the query, which will be a string type, check to make sure that the directory listed exists. If the directory listed does not exist, I need to be able to create the directory. (For example, if the above query returns the output location "C:\test\EDI\", I need to be able to test if that location exists. If it exists then you move onto writing data to a file named abc.txt, for simplicity of testing. If the path does not exist, then the VB .NET 2010 code needs to create the directory before writing to the output file named "abc.txt") Any help that you would be able to provide with this task would be greatly appreciated. Also, how would I be able to test whether or not the location that is being written to is a "Shared" resource on a network where others are able to access the same folder via a server or a cluster of workstations that are on a network? (This would be done using VB .NET 2010 code.)
Who is Participating?
Carlos VillegasFull Stack .NET DeveloperCommented:
Hi, you can try this:
Dim path As String = String.Empty
' Connect to your DB
' More connection string info at
Using cn As New System.Data.SqlClient.SqlConnection("MyConnectionString")
    Dim cm As New System.Data.SqlClient.SqlCommand("Select TOP 1 EDIOutputPath From SystemParms", cn)
    ' Open your connection
    ' Retrieve the value of your query (First row, first column)
    path = Convert.ToString(cm.ExecuteScalar())
End Using

' Check if directory exist
If Not System.IO.Directory.Exists(path) Then
    ' Create directory
End If

' Create the file (file contents optional)
System.IO.File.WriteAllText(System.IO.Path.Combine(path, "abc.txt"), "")
End Sub

Open in new window

Here's the check for the directory and if not found the create
dim FI as new io.fileinfo(your path)
IF not IO.Directory.exists (fi.directoryname) then

Carlos VillegasFull Stack .NET DeveloperCommented:
Oops, remove the "End Sub" at line 20.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.