How can I use File.AppendAllText and add to it a new line?

Uniter 3D
public static void Save(string saveString)
    {
        File.AppendAllText(SAVE_FOLDER + "/" + "savegame.txt", saveString);
    }

The method is being called twice or even more times and each time with another saveString. The content of the saved file is like this :

{"objects":[{"Key":"367f6ac2-6fd3-4c99-91e5-cc335a104ac4","Value":"{\"s1\":false}"}],"instanceID":0,"position":{"x":8.140000343322754,"y":0.0,"z":0.0},"scaling":{"x":1.0,"y":1.0,"z":1.0},"rotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0}}{"objects":[{"Key":"ecb45f8e-463c-4fe3-a436-5d836165bcce","Value":"{\"s1\":false}"}],"instanceID":0,"position":{"x":-11.229999542236329,"y":0.0,"z":8.920000076293946},"scaling":{"x":1.0,"y":1.0,"z":1.0},"rotation":{"x":0.0,"y":0.0,"z":0.0,"w":1.0}}

And I want to format it to something nicer to be easier to look at maybe adding an empty line between each string ? Or some other format ?

This is how I'm saving it with json :

public void Save()
    {
        SaveObject saveObject = new SaveObject();
        for (int i = 0; i < objectsToSave.Count; i++)
        {
            var x = objectsToSave[i].GetComponents<Component>();
            var y = x.Where(component => component is IStateQuery).ToList();
            List<KeyToValue> myObjects = new List<KeyToValue>();
            foreach(var z in y)
            {
                var w = z as IStateQuery;
                myObjects.Add(new KeyToValue(w.UniqueId.ToString(), w.GetState()));
                
            }
            saveObject.position = objectsToSave[i].position;
            saveObject.scaling = objectsToSave[i].localScale;
            saveObject.rotation = objectsToSave[i].rotation;

            saveObject.objects = myObjects;


            string json = JsonUtility.ToJson(saveObject);

            SaveSystem.Save(json);
        }
    }

But I don't like the format of the content in the file.

I tried to add Environment.NewLine :

File.AppendAllText(SAVE_FOLDER + "/" + "savegame.txt" + Environment.NewLine, saveString);

But it's giving me error :

ArgumentException: Illegal characters in path.

Athanasios Kataras

I think your fix might be as simple as this:

File.AppendAllText(SAVE_FOLDER + "/" + "savegame.txt" , Environment.NewLine + saveString);
// or even better at the end
File.AppendAllText(SAVE_FOLDER + "/" + "savegame.txt" ,  saveString + Environment.NewLine);

You are adding the new line to the filename and it is indeed invalid. Add it before or after your content and you'll do fine.

By the way, the content of the file, is not a valid json. While each line is, the total file is not as the following syntax is invalid

{}
{}

If you want it all to be a JSon object you'll need something like this

[
   {},
   {}
]

Este artigo é coletado da Internet.

Se houver alguma infração, entre em [email protected] Delete.

editar em
0

deixe-me dizer algumas palavras

0comentários
loginDepois de participar da revisão

Artigos relacionados

How can I create a new "file type" in the command line?

How can I use each line of a file as an input switch in bash?

I would like to add a new line in SELECT statement in SSMS. how can it be done?

How can I add line break in userform?

How can I use RegEx to find a term, if the term is broken by a new-line in the searched text

How can I insert a new line into a text file into every other 2 lines?

How can I add a new tab dynamically?

How can I add a new column with forecasts?

How can I use VBA to add a totals row at the end of new table

Java: How to add a new line of String to the existing text file?

How can I read userinput with the newline in python, that prints as a new line?

How to add new line in FormattedString

how can i add points to geom_line plot in ggplot

How can I add a line between output text?

How can I add line breaks in a wchar_t array?

How can I add line numbers to a textarea using an ordered list?

How can I add an new property to a list item in flutter / dart?

How can i tell the program to add a new field to an object?

How can I add a new column to dataframe in RCpp?

How can i add a new empty row in a DataGridView?

How can I add new values to the beginning of an existing array?

How can I add new column in Julia Dataframe

How can I use to the stream extraction operator to read a file assuming that only the last line will have errors of not containing 3 values

In laravel blade file javascript stops working after some time when i add new line of code

How can I use getopt with command line arguments in Swift 3?

How can I use getopt with command line arguments in Swift 3?

How can I use broadcasting to code my program in one line?

How can i cast the .nth() line in a file as an integer?

How can I skip the first and the last line of a file in PHP

TOP lista

  1. 1

    R Shiny: use HTML em funções (como textInput, checkboxGroupInput)

  2. 2

    O Chromium e o Firefox exibem as cores de maneira diferente e não sei qual deles está fazendo certo

  3. 3

    Como assinar digitalmente um documento PDF com assinatura e texto visíveis usando Java

  4. 4

    R Folheto. Dados de pontos de grupo em células para resumir muitos pontos de dados

  5. 5

    Gerenciar recurso shake de Windows Aero com barra de título personalizado

  6. 6

    Como obter dados API adequados para o aplicativo angular?

  7. 7

    UITextView não está exibindo texto longo

  8. 8

    Por que meus intervalos de confiança de 95% da minha regressão multivariada estão sendo plotados como uma linha de loess?

  9. 9

    Acessando relatório de campanhas na AdMob usando a API do Adsense

  10. 10

    Usando o plug-in Platform.js do Google

  11. 11

    Como posso modificar esse algoritmo de linha de visada para aceitar raios que passam pelos cantos?

  12. 12

    Dependência circular de diálogo personalizado

  13. 13

    Coloque uma caixa de texto HTML em uma imagem em uma posição fixa para site para desktop e celular

  14. 14

    iOS: como adicionar sombra projetada e sombra de traço no UIView?

  15. 15

    Como usar a caixa de diálogo de seleção de nomes com VBA para enviar e-mail para mais de um destinatário?

  16. 16

    Tabela CSS: barra de rolagem para a primeira coluna e largura automática para a coluna restante

  17. 17

    How to create dynamic navigation menu select from database using Codeigniter?

  18. 18

    Converter valores de linha SQL em colunas

  19. 19

    ChartJS, várias linhas no rótulo do gráfico de barras

  20. 20

    用@StyleableRes注释的getStyledAttributes。禁止警告

  21. 21

    não é possível adicionar dependência para com.google.android.gms.tasks.OnSuccessListener

quentelabel

Arquivo