Search code examples
c#unity-game-enginecreate-directory

Unity3d: handle spaces in file names


How do I open/create the files having spaces in their name? I have the following piece of code:

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.

Here GameInfo.gameTitle.ToString() returns "Some game name" and the resulting file name is thus "Some: game name - 2-12-2018-23-14-10.txt". On executing this piece of code, a new folder with the name "Some" is created instead of a new text file with name "Some game name - 2-12-2018-23-14-10.txt". How do I escape the spaces in the file name? I tried using WWW.EscapeURL and it works, but it appends weird % characters in between as expected. Is there a better solution to this?


Solution

  • No need to create a FileInfo, use

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

    The : inside your files name is confusing the create command. There are several characters that are forbidden inside Filenames which you should remove before trying to save that:

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

    Or better use Path.GetInvalidPathChars() but beware of

    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).

    You can try this:

    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();
    }