Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way of making strings file-path safe in c#?

My program will take arbitrary strings from the internet and use them for file names. Is there a simple way to remove the bad characters from these strings or do I need to write a custom function for this?

like image 956
Martin Doms Avatar asked Dec 02 '08 06:12

Martin Doms


People also ask

How long can file names be in Windows 10?

In Windows 10, you can enable long file name support, which allows file names up to 32,767 characters (although you lose a few characters for mandatory characters that are part of the name). To enable this, perform the following: Start the registry editor (regedit.exe)

What characters are allowed in a file name in Windows?

Supported characters for a file name are letters, numbers, spaces, and ( ) _ - , . *Please note file names should be limited to 100 characters. Characters that are NOT supported include, but are not limited to: @ $ % & \ / : * ? " ' < > | ~ ` # ^ + = { } [ ] ; !

How long can file names be?

The Windows API imposes a maximum filename length such that a filename, including the file path to get to the file, can't exceed 255-260 characters.

What is the maximum character length of a path folders and filenames?

Causes: By default, Windows uses a path length limitation (MAX_PATH) of 256 characters: Naming Files, Paths, and Namespaces.


1 Answers

Ugh, I hate it when people try to guess at which characters are valid. Besides being completely non-portable (always thinking about Mono), both of the earlier comments missed more 25 invalid characters.

foreach (var c in Path.GetInvalidFileNameChars())  {    fileName = fileName.Replace(c, '-');  } 

Or in VB:

'Clean just a filename Dim filename As String = "salmnas dlajhdla kjha;dmas'lkasn" For Each c In IO.Path.GetInvalidFileNameChars     filename = filename.Replace(c, "") Next  'See also IO.Path.GetInvalidPathChars 
like image 154
Jonathan Allen Avatar answered Nov 05 '22 11:11

Jonathan Allen