2

i am new to visual basic and i'm trying to create a file with this code

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim curboard As String = comboard.SelectedItem
    Dim curstd As String = comstd.SelectedItem
    Dim curdiv As String = comdiv.SelectedItem
    Dim curmed As String = commed.SelectedItem
    Dim filepath As String = "c:\program files\School Attandance Management System 1.0\data\" & curdiv & ".samsclass"

    Try
        File.Create(filepath)
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try


End Sub

This outputs

Illigal characters in path

comdiv,comstd,commed and comboard are comboboxes Please let me know how to concatenete the variables into filepath ?

6
  • 1
    What is the value of curdiv variable? Commented May 15, 2013 at 12:27
  • possible duplicate of How to remove illegal characters from path and filenames? This solution will allow you to remove those invalid characters from the filepath variable. Commented May 15, 2013 at 12:28
  • curdiv's value is the string which user will select in combobox Commented May 15, 2013 at 12:33
  • Yes, of course is the string selected, but I wish to know its actual value. Your path is formally correct but without seeing the actual value of curdiv is not possible to say if there is some invalid chars there Commented May 15, 2013 at 12:36
  • 1
    @TheFabricio not in VB.NET (backslash as escape) Commented May 15, 2013 at 12:46

1 Answer 1

6

To concatenate strings to form valid file paths you should use the Path class and its method Path.Combine

Path.Combine("c:\program files\School Attandance Management System 1.0\data", 
             curdiv, ".samsclass")

Notice how the method accepts an array of strings and combine them together to form a valid file path inserting the correct path separator where needed.

Of course the variable curdiv itself should not contains invalid filename characters as the ones you can obtain from the method GetInvalidFileNameChars

You could try to remove the invalid chars with code like this, but the correct approach should be to not allow invalid names in the combobox

Dim invalidFileChars() As Char = Path.GetInvalidFileNameChars()
for each c in invalidFileChars
    curdiv = curdiv.Replace(c.ToString(), "")
Next
Sign up to request clarification or add additional context in comments.

2 Comments

Glad for you, also note that my answer assumed that curdiv is a folder not a filename, I will update the answer now
@H4x0r, If Steve has answered your question you should press the tick on the left to show this as the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.