Easiest way to check if an arbitrary String is a valid filename
Check whether filename.IndexOfAny(Path.GetInvalidFileNameChars()) < 0
and !File.Exists(Path.Combine(someFolder, filename))
How do I check if a given string is a legal/valid file name under Windows?
You can get a list of invalid characters from Path.GetInvalidPathChars
and GetInvalidFileNameChars
.
UPD: See Steve Cooper's suggestion on how to use these in a regular expression.
UPD2: Note that according to the Remarks section in MSDN "The array returned from this method is not guaranteed to contain the complete set of characters that are invalid in file and directory names." The answer provided by sixlettervaliables goes into more details.
Check if string is valid filename
You may have a look in php's basename
function, it will return with filename, see example below:
$file = '../../abc.txt';
echo basename($file); //output: abc.txt
Note: basename
gets you the file name from path string irrespective of file physically exists or not. file_exists
function can be used to verify that the file physically exists.
How to make a valid Windows filename from an arbitrary string?
Try something like this:
string fileName = "something";
foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
fileName = fileName.Replace(c, '_');
}
Edit:
Since GetInvalidFileNameChars()
will return 10 or 15 chars, it's better to use a StringBuilder
instead of a simple string; the original version will take longer and consume more memory.
How to make a valid filename from an arbitrary string in Javascript?
Huge thanks to Kelvin's answer!
I quickly compiled it into a function. The final code I used is:
function convertToValidFilename(string) {
return (string.replace(/[\/|\\:*?"<>]/g, " "));
}
var string = 'Un éléphant à l\'orée du bois/An elephant at the edge of the woods".txt';
console.log("Before = ", string);
console.log("After = ", convertToValidFilename(string));
This results in the output:
Before = Un éléphant à l'orée du bois/An elephant at the edge of the woods".txt
After = Un éléphant à l orée du bois An elephant at the edge of the woods .txt
Turn a string into a valid filename?
You can look at the Django framework for how they create a "slug" from arbitrary text. A slug is URL- and filename- friendly.
The Django text utils define a function, slugify()
, that's probably the gold standard for this kind of thing. Essentially, their code is the following.
import unicodedata
import re
def slugify(value, allow_unicode=False):
"""
Taken from https://github.com/django/django/blob/master/django/utils/text.py
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
dashes to single dashes. Remove characters that aren't alphanumerics,
underscores, or hyphens. Convert to lowercase. Also strip leading and
trailing whitespace, dashes, and underscores.
"""
value = str(value)
if allow_unicode:
value = unicodedata.normalize('NFKC', value)
else:
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore').decode('ascii')
value = re.sub(r'[^\w\s-]', '', value.lower())
return re.sub(r'[-\s]+', '-', value).strip('-_')
And the older version:
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
"""
import unicodedata
value = unicodedata.normalize('NFKD', value).encode('ascii', 'ignore')
value = unicode(re.sub('[^\w\s-]', '', value).strip().lower())
value = unicode(re.sub('[-\s]+', '-', value))
# ...
return value
There's more, but I left it out, since it doesn't address slugification, but escaping.
Related Topics
C# Web API Sending Body Data in Http Post Rest Client
How to Check for a Valid Base64 Encoded String
Lambda Where Id Does Not Exist in Another List
How to Ignore Convert to Nullable in Lambda Expressions
How to Remove Windows Credentials
Convert a List of Objects from One Type to Another Using Lambda Expression
Find First Digit of a Number Using Only Integer Operations
How to Redirect to Login Page If Session Is Not Available in MVC
Update Value in Datatable from Another Datatable
Unicode Characters Replace from String Using C#
How to Create ASP.NET Identity Tables in an Already Created Database Using Code First
Generate All Combinations from Multiple (N) Lists
Select Multiple Records Based on List of Id'S With Linq
Getting User Input and Adding It to an Array At C#