gpt4 book ai didi

c# - Unity3d:处理文件名中的空格

转载 作者:太空宇宙 更新时间:2023-11-03 20:57:40 25 4
gpt4 key购买 nike

如何打开/创建名称中包含空格的文件?我有以下代码:

FILENAME = (GameInfo.gameTitle.ToString() + " - " + month + "-" + day + "-" + year + "-" + hour + "-" + minute + "-" + second);
// The dump file holds all the emotion measurements for each frame. Put in a separate file to not clog other data.
DUMPNAME = FILENAME + "-EMOTION-DUMP.txt";
FILENAME += ".txt";

Debug.Log("FILENAME==== " + FILENAME);
FileInfo file = new FileInfo(FILENAME);
file.Directory.Create(); // If it already exists, this call does nothing, so no fear.

此处 GameInfo.gameTitle.ToString() 返回“Some game name”,因此生成的文件名为“Some: game name - 2-12-2018-23-14-10.txt ”。在执行这段代码时,将创建一个名为“Some”的新文件夹,而不是一个名为“Some game name - 2-12-2018-23-14-10.txt”的新文本文件。如何转义文件名中的空格?我尝试使用 WWW.EscapeURL 并且它有效,但它按预期在两者之间附加了奇怪的 % 字符。对此有更好的解决方案吗?

最佳答案

无需创建FileInfo,使用

System.IO.Directory.CreateDirectory("./"+FILENAME); // with a fixed file name

文件名中的 : 混淆了创建命令。文件名中有几个禁止使用的字符,您应该在尝试保存之前将其删除:

var forbidden = new char[] { '/', '\\', '?', '*', ':', '<', '>', '|', '\"' };

或者更好地使用Path.GetInvalidPathChars()但要小心

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 (<), greater than (>), pipe (|), backspace (\b), null (\0) and tab (\t).

你可以试试这个:

static string FixFileName (string fn)
{
var forbidden = new char[] { '/', '\\', '?', '*', ':', '<', '>', '|', '\"' };

var sb = new StringBuilder (fn);
for (int i = 0; i < sb.Length; i++)
{
if ((int)sb[i] < 32 || forbidden.Contains (sb[i]))
sb[i] = '-';
}

return sb.ToString ().Trim();
}

关于c# - Unity3d:处理文件名中的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48760616/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com