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

标签 c# unity3d create-directory

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

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/

相关文章:

c# - Unity 在没有 IsTrigger 的情况下使用 OnCollisionEnter2D 检测碰撞

c++ - 如何在不使用 C++ 中的宽字符串的情况下创建目录?

python - 使用单个 os.mkdir 函数生成超过 1 个目录 (Python)

c# - 在反序列化期间忽略属性

c# - Unity C# - 数组索引超出范围

c# - 我们如何在 WPF 应用程序中进行空闲时间处理?

android - Unity ARFoundation Gradle构建失败-拒绝last-build.bin访问

c# - Directory.CreateDirectory 对路径的访问被拒绝?

c# - 无法将类型 'void' 隐式转换为 'object' asp.net.MVC

c# - 返回传递给方法的值