-1

我的路径是 UTF-16 字符串。他们中的大多数只使用 ASCII 集,所以像这样的文件名将test被存储为

T \x00 E \x00 S \x00 T \x00

Encoding.Unicode.GetString(bytes)用来读取字符串并且它工作正常(当我将它们打印到控制台或表单控件时,它会按我的预期显示),但是当我想使用以下代码实际创建具有给定文件名的文件时

BinaryWriter outFile = new BinaryWriter(File.OpenWrite(path));

我得到一个例外

Unhandled Exception: System.ArgumentException: Illegal characters in path.
   at System.IO.Path.CheckInvalidPathChars(String path)
   at System.IO.Path.GetFileName(String path)

这可能是因为那里有空字符(可能它在内部存储了原始字节数组),但我不知道如何处理它。不过,并非所有字符串都是 ASCII,并且一些字符使用两个字节。

更新:

原来非法字节只是填充到字符串中的空字节。但是,我不能简单地去除所有尾随空字节,但我也不知道字符串的长度。如何从每个字符存储在 n 个字节中的字符串中去除空字节?

4

2 回答 2

2

来自 MSDN 上的“Path.GetInvalidPathChars”

完整的无效字符集可能因文件系统而异。例如,在基于 Windows 的桌面平台上,无效路径字符可能包括 ASCII/Unicode 字符 1 到 31,以及引号 (")、小于 (<)、大于 (>)、竖线 (|)、退格 ( \b)、空 (\0) 和制表符 (\t)。

您可以Path.GetInvalidPathChars用作过滤器。将输入字符串复制到输出字符串,同时过滤与Path.CheckInvalidPathChars.

这是我制作的一个例子:

string input = @"This <path> ""contains"" |some| ~invalid~ characters";

var invalidChars = Path.GetInvalidPathChars();

string output = input.Aggregate(new StringBuilder(), (sb, c) => invalidChars.Contains(c) ? sb : sb.Append(c), sb => sb.ToString());

// output contains: This path contains some ~invalid~ characters

请注意,大多数符号都会被过滤掉,但波浪号不会,因为它们是有效的路径字符。

于 2012-08-19T21:19:39.193 回答
1

您最有可能收到此错误,因为您的路径包含一个无效字符,如果您调用Path.GetInvalidPathChars().

其中一些字符是",<和。|>

因为您已经使用Encoding.Unicode.GetString此问题对字符串进行了解码,所以与任何 UNICODE 编码问题无关。

这是一些简单(但不是很有效)的代码,可以用下划线替换路径中的无效字符:

var stringBuilder = path
  .Select(c => Path.GetInvalidPathChars().Contains(c) ? '_' : c)
  .Aggregate(new StringBuilder(), (a, c) => a.Append(c));
path = stringBuilder.ToString();
于 2012-08-19T21:20:08.607 回答