File Safe Name

OSVBNET 1,386 Reputation points

Is there any built-in method to get the safe name for a folder I'm gonna create?
I'm going to use Directory.CreateDirectory to make some folders, the names are parsed from a source and need to filter out illegal characters which are not allowed in the file/folder names!

There's a full list here:

Just wonder if there's a built-in .net method to validate?

An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,562 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Dewayne Basnett 1,041 Reputation points

    A thought

        Private Function SafePath(path As String) As String  
            Static InvalidPathChars() As Char = IO.Path.GetInvalidPathChars  
            Dim rv As String = path  
            Catch ex As Exception  
                Dim p() As String = rv.Split(InvalidPathChars)  
                rv = String.Join("_"c, p)  
            End Try  
            Return rv  
        End Function  
    1 person found this answer helpful.
    0 comments No comments

  2. Karen Payne MVP 35,026 Reputation points

    I removed my first response in favor of the following.

    Option Strict On  
    Imports System.IO  
    Imports System.Text.RegularExpressions  
    Module Program  
        Sub Main(args As String())  
            Dim folderNames() As String = {"|OED", "!OED~", "<<Dir", "(Me&^"}  
            For Each name In folderNames  
                Console.WriteLine($"{name} is valid? {IsValidFolderName(name)}")  
        End Sub  
    End Module  
    Public Module Directory  
        Private ReadOnly _illegalInFileName As New Regex($"[{Regex.Escape(  
            New String(Path.GetInvalidFileNameChars()))}]", RegexOptions.Compiled)  
        Public Function IsValidFolderName(folder As String) As Boolean  
            Return _illegalInFileName.Replace(folder, "") = folder  
        End Function  
    End Module  
    0 comments No comments