Unity3d:处理文件名中的空格

Unity3d: handle spaces in file names

如何 open/create 文件名中有空格?我有以下代码:

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() returns "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 ([=15=]) 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();
}