Search code examples
c#unity-game-enginefilestream

How to use a variable as a file name in a file stream in Unity


I'm working on saving a list as a binary file in my game. The problem is I want to use a variable taken from an input field and use it as the name in which to save the stream. Unfortunately I can't just escape using quotes as it gives me a squiggly red line under the variable.

FileStream fs = File.Create(Application.persistentDataPath + "/Items/+"MapNameField"+.dat");

Help would be greatly appreciated. Thanks in advance!


Solution

  • Your +'s are in the wrong spot

    "/Items/+"MapNameField"+.dat"
    

    Needs to be:

    "/Items/"+MapNameField+".dat"
    

    Or, better yet, use Path.Combine as @derHugo suggested:

    File.Create(Path.Combine(Application.persistentDataPath, "Items", MapNameField + ".dat")