File Safe Name

OSVBNET 1,386 Reputation points
2022-06-24T12:12:14.877+00:00

Hello,
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:
https://learn.microsoft.com/en-us/windows/win32/fileio/naming-a-file

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

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

2 answers

Sort by: Most helpful
  1. Dewayne Basnett 1,116 Reputation points
    2022-06-24T13:51:44.51+00:00

    A thought

        Private Function SafePath(path As String) As String  
            Static InvalidPathChars() As Char = IO.Path.GetInvalidPathChars  
            Dim rv As String = path  
            Try  
                IO.Path.GetFullPath(rv)  
            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,196 Reputation points
    2022-06-24T12:25:18.787+00:00

    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)}")  
            Next  
      
            Console.ReadLine()  
      
        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