- «Invalid characters» error when you sync files from Windows Explorer to OneDrive
- Problem
- Solution
- More information
- Fixing invalid characters and colliding file names
- Colliding filenames
- Invalid characters and filenames
- Invalid filenames on Windows
- How to fix invalid filenames
- doctaphred / ntfs-filenames.txt
- This comment has been minimized.
- sagi053 commented Mar 24, 2020
- This comment has been minimized.
- doctaphred commented Mar 25, 2020
- Path. Get Invalid File Name Chars Метод
- Определение
- Возвращаемое значение
- Примеры
- Комментарии
- How do I check for illegal characters in a path?
- 9 Answers 9
«Invalid characters» error when you sync files from Windows Explorer to OneDrive
Problem
When you use Microsoft OneDrive for work or school (formerly Microsoft SkyDrive Pro) to sync files from Windows Explorer to a Microsoft SharePoint site, some files may not sync as expected. Instead, a red X is displayed on the file icon in Windows Explorer and then you experience one of the following problems:
Note: This article applies only to the previous OneDrive for work or schoolsync app (groove.exe). In most cases, we recommend that you use the newer OneDrive sync app (onedrive.exe) instead. Which OneDrive app?
In the Microsoft Office Upload Center, you receive the following error message:
Upload Failed
Invalid characters
In OneDrive. Sync problems appears in the notification area. When you click View sync problems, you receive the following message:
X item can’t be synced with OneDrive.
NOTE: X is the number of files that OneDrive is trying to sync.
Under the Error column, the following message is also present:
This file name contains invalid characters.
NOTE: This issue occurs if you’re syncing files to Microsoft Microsoft 365 SharePoint Online or Microsoft SharePoint Server 2013.
Solution
To resolve this issue, delete any invalid characters from the file name of the Windows Explorer file that you’re trying to upload to the SharePoint site.
After you have deleted unsupported characters from the file name, the file will sync with OneDrive.
More information
This issue occurs because the characters that are listed in the «Solution» section are not supported by OneDrive.
For more information about OneDrive, go to What is OneDrive?
Fixing invalid characters and colliding file names
When you try to create, rename or save files, two common errors might occur that will prevent your file from syncing: invalid characters and colliding filenames.
Colliding filenames
This error happens when you try to create, rename or save a file to a folder that already contains a file with the same name.
There are two rules to watch out for when you name your files:
- Tresorit filenames are case insensitive, which means that A.txt and a.txt are considered the same.
- Filenames with the same Unicode normalization are considered the same.
Invalid characters and filenames
You can upload all files to the cloud with a filename that doesn’t contain any control characters or a / (forward slash). Also, the filename can’t be any of the filenames reserved by Tresorit application (. and ..).
Invalid filenames on Windows
If you wish to download your files to a Windows Operation System, there are additional rules the filename needs to comply with.
- The filename doesn’t contain any of the following characters: » (double quote), * (asterisk), (greater than), ? (question mark), \ (backslash), | (pipe), / (forward slash), : (colon)
- The filename can’t end with a space or a period
- The filename can’t contain any of the names reserved by Windows
How to fix invalid filenames
Validation rules are stricter on Windows than on any other devices, that’s why in some cases you will need to rename files when you download them from the cloud. When a file contains invalid characters, you will see a notification in orange in your Tresorit client.
📝 Note: If you don’t use Tresorit on a Windows PC, you can ignore this notification. However, we advise you to review your filenames before you share your files with others — invalid filenames won’t sync on Windows devices.
- Click the notification arrow.
- A list of filename conflicts will appear on a pop-up. You can either choose to rename all files using the suggestions or edit filenames one-by-one.
Click on a conflict file, then click Rename.
doctaphred / ntfs-filenames.txt
Information from https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file : |
Use any character in the current code page for a name, including Unicode |
characters and characters in the extended character set (128–255), except |
for the following: |
— The following reserved characters: |
(greater than) |
: (colon) |
» (double quote) |
/ (forward slash) |
\ (backslash) |
| (vertical bar or pipe) |
? (question mark) |
* (asterisk) |
— Integer value zero, sometimes referred to as the ASCII NUL character. |
— Characters whose integer representations are in the range from 1 through |
31, except for alternate data streams where these characters are |
allowed. For more information about file streams, see File Streams. |
— Any other character that the target file system does not allow. |
— Do not use the following reserved names for the name of a file: |
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, |
COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9. |
Also avoid these names followed immediately by an extension; for |
example, NUL.txt is not recommended. |
— Do not end a file or directory name with a space or a period. Although |
the underlying file system may support such names, the Windows shell and |
user interface does not. However, it is acceptable to specify a period |
as the first character of a name. For example, «.temp». |
— |
Handy list to copy/paste: |
<>:»/\|?* |
— |
Note: Other OSs and file systems may vary; but in general, the only forbidden characters |
in filenames on Unix-like systems appear to be the forward slash (/) and the null byte. |
This comment has been minimized.
Copy link Quote reply
sagi053 commented Mar 24, 2020
Nice regex to find and replace invalid chars in file name.
[<>:»/\|?*]
example:
javascript:
«my file is * invalid ?.pdf».replace(/[<>:»/\|?*]/g,»«);
php:
$fileName = preg_replace(‘/[<>:»/\|?*]/’,’‘,’my file is * invalid ?.pdf’);
c#
var fileName = (new Regex(@»[<>:»»/\|?*]»)).Replace(«my file is * invalid ?.pdf»,»_»);
This comment has been minimized.
Copy link Quote reply
doctaphred commented Mar 25, 2020
Thanks for the contribution! Couple of notes:
\ is the escape character in most regex engines, so you’ll need to repeat it to make sure it gets included in the character class and doesn’t just escape the | after it: [<>:»/\\|?*] / «my file is \\ invalid ?.pdf».replace(/[<>:»/\\|?*]/g, «_»);
Also, I’m not super confident in my PHP knowledge, but I think you’ll need to double-escape the backslash: once because PHP treats it as an escape character in the string literal (even when using single quotes), and a second time for the regex engine. So I think you’ll need a total of four \ characters: ‘/[<>:»/\\\\|?*]/’ (gross).
(It looks like C# uses the @ prefix to denote verbatim strings, which look like Python’s raw strings, and should only need a single escape for the regex engine. JS does not (yet) seem to offer unescaped string literals, but RegExp literals don’t apply the additional layer of escaping.)
Path. Get Invalid File Name Chars Метод
Определение
Возвращает массив, содержащий символы, которые не разрешены в именах файлов. Gets an array containing the characters that are not allowed in file names.
Возвращаемое значение
Массив, содержащий символы, которые не разрешены в именах файлов. An array containing the characters that are not allowed in file names.
Примеры
В следующем примере демонстрируется GetInvalidFileNameChars метод и GetInvalidPathChars метод для получения недопустимых символов. The following example demonstrates the GetInvalidFileNameChars method and the GetInvalidPathChars method to retrieve invalid characters.
Комментарии
Массив, возвращаемый из этого метода, не обязательно должен содержать полный набор символов, недопустимых в именах файлов и каталогов. 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 full set of invalid characters can vary by file system. Например, на настольных платформах Windows недопустимые символы пути могут содержать символы ASCII/Unicode от 1 до 31, а также кавычки («), меньше ( ), вертикальный (|), Backspace (\b), null (\ 0) и Tab (\t). For example, on Windows-based desktop platforms, invalid path characters might include ASCII/Unicode characters 1 through 31, as well as quote («), less than ( ), pipe (|), backspace (\b), null (\0) and tab (\t).
How do I check for illegal characters in a path?
Is there a way to check if a String meant for a path has invalid characters, in .Net? I know I could iterate over each character in Path.InvalidPathChars to see if my String contained one, but I’d prefer a simple, perhaps more formal, solution.
I’ve found I still get an exception if I only check against Get
Update:
I’ve found GetInvalidPathChars does not cover every invalid path character. GetInvalidFileNameChars has 5 more, including ‘?’, which I’ve come across. I’m going to switch to that, and I’ll report back if it, too, proves to be inadequate.
Update 2:
GetInvalidFileNameChars is definitely not what I want. It contains ‘:’, which any absolute path is going to contain («C:\whatever»). I think I’m just going to have to use GetInvalidPathChars after all, and add in ‘?’ and any other characters that cause me problems as they come up. Better solutions welcome.
9 Answers 9
InvalidPathChars is deprecated. Use GetInvalidPathChars() instead:
Edit: Slightly longer, but handles path vs file invalid chars in one function:
Be careful when relying on Path.GetInvalidFileNameChars , which may not be as reliable as you’d think. Notice the following remark in the MSDN documentation on Path.GetInvalidFileNameChars :
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 full set of invalid characters can vary by file system. For example, on Windows-based desktop platforms, invalid path characters might include ASCII/Unicode characters 1 through 31, as well as quote («), less than ( ), pipe (|), backspace (\b), null (\0) and tab (\t).
It’s not any better with Path.GetInvalidPathChars method. It contains the exact same remark.
I ended up borrowing and combining a few internal .NET implementations to come up with a performant method:
I then used it like so but also wrapped it up in a try/catch block for safety:
As of .NET 4.7.2, Path.GetInvalidFileNameChars() reports the following 41 ‘bad’ characters.
As noted by another poster, this is a proper superset of the set of characters returned by Path.GetInvalidPathChars() .
The following function detects the exact set of 41 characters shown above:
It’s probably too late for you, but may help somebody else. I faced the same issue and needed to find a reliable way to sanitize a path.
Here is what I ended up using, in 3 steps:
Step 1: Custom cleaning.
Step 2: Check any invalid characters not yet removed.
A an extra verification step, I use the Path.GetInvalidPathChars() method posted above to detect any potential invalid characters not yet removed.
Step 3: Clean any special characters detected in Step 2.
And finally, I use this method as final step to clean anything left. (from How to remove illegal characters from path and filenames?):
I log any invalid character not cleaned in the first step. I choose to go that way to improve my custom method as soon as a ‘leak’ is detected. I can’t rely on the Path.GetInvalidFileNameChars() because of the following statement a reported above (from 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. «
It may not be the ideal solution, but given the context of my application and the level of reliability required, this is the best solution I found.