问题描述
我正在构建一个可以在 Windows 和 Ubuntu 系统上运行的 .Net Core 2.0 控制台应用程序.我有一个需要转换为安全文件名的字符串.目前我正在使用以下代码来实现这一点:
I'm building a .Net Core 2.0 console application that will run on both Windows and Ubuntu systems. I have a string that needs to be converted into a safe file name. Currently I'm using the following code to achieve this:
var safeName = string.Join("-", name.Split(Path.GetInvalidFileNameChars()));
它可以工作,但它会在不同的操作系统上产生不同的结果,因为 Linux 允许 Windows 不允许的字符.我喜欢在所有系统上产生相同结果的解决方案.
It works, but it will produce different results on different operating system as Linux allows characters that Windows will not allow. I like a solution that produces the same result on all of the systems.
是否有一个跨平台版本的GetInvalidFileNameChars
可以返回所有平台的字符?
Is there a cross platform version of GetInvalidFileNameChars
that will return characters for all platforms?
推荐答案
我认为 BCL 中没有跨平台"版本,但您可以通过复制 Windows 版本的 GetInvalidFileNameChars,因为 Unix 版本 只是其中的一个子集,它们不太可能经常更改:
I don't think there is a "cross-platform" version in the BCL, but you can easily make one yourself by copying the Windows version of GetInvalidFileNameChars, because the Unix version is just a subset of these and they're not likely to change often:
public static char[] GetInvalidFileNameChars() => new char[]
{
'"', '<', '>', '|', ' ',
(char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10,
(char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20,
(char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30,
(char)31, ':', '*', '?', '\', '/'
};
这篇关于DotNetCore:GetInvalidFileNameChars 的跨平台版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!