Write to the right line of the file and find parameters present in it?

Asked

Viewed 469 times

1

I created the file:

FileInfo arq = new FileInfo("C:\\ProgramData\\dataMinGSMFans");

if (arq.Exists == false)
    File.Create("C:\\ProgramData\\dataMinGSMFans").Close();

In a form I will see if it has content and assign this content to form objects (as in this case I took the color):

StreamReader file = new StreamReader(@"C:\\ProgramData\\dataMinGSMFans");
while ((line = file.ReadLine()) != null)
{
    if (line.Contains("c1-"))
        cor1.BackColor = Color.FromName(line.Replace("c1-", "").Trim());
    else if (line.Contains("c2-"))
        cor2.BackColor = Color.FromName(line.Replace("c2-", "").Trim());
}
file.Close();

To save in the file I am using different parameters, as a key to identify what I am saving, as c1- and c2-, cor1 and cor2:

var conteudo = string.Format("c1-{0}{1}", corPri.Color.Name, Environment.NewLine);
File.WriteAllText(@"C:\\ProgramData\\dataMinGSMFans", conteudo);

.
.
.

var conteudo = string.Format("c2-{0}{1}", corSec.Color.Name, Environment.NewLine);
File.WriteAllText(@"C:\\ProgramData\\dataMinGSMFans", conteudo);

The problem is: It is always writing in the first line of the file, and deleting the other one I had written, I want to know how to write the content in an empty line of the file without deleting the whole file, and if you already have a line of the parameter c1- or c2- (cor1 and cor2) it replace the existing line by changing only the value after the -

  • 2

    I won’t try to answer because I don’t know if I understand the question and if I did I won’t think about all the logic of it (the conception of how to do this must also be wrong but you can’t even know without seeing the whole intention of the code) But I can help you by telling you that the whole conception of how to work files is wrong. Do some research and you have some questions about it. Some teach this way and are wrong, others show correctly how to work with files in a general way.

  • Thank you, I will give a further search, the places I researched were like this, even here, in a question was with a similar answer, but I will continue the search.

  • 1

    That’s what I said, a lot of people learned wrong and teach wrong.

1 answer

1


File.Writealltext method (String, String)

Creates a new file, writes the specified string to the file, and then closes the file. If the destination file already exists, it will be overwritten.

So to continue using this method, you need to load and manipulate before writing all the data of your file into a string, modify it as you like and then save it.

//carregando os dados do arquivo
string dados = null;
while ((line = file.ReadLine()) != null)
{
    if(dados == null) dados = line;
    else dados += "\n"+line;
}

//modificar os parametros que vc quiser...
public static string modificarParametros(string dadosDoArquivo, string key, string valor)
{
    if(dadosDoArquivo == null) return null;
    string[] linhas = dados.Split(new char[]{'\n'});
    string saida = null;
    bool encontrado = false;
    foreach(string linha in linhas)
    {
        if(linha.Contains(key))
        {
            encontrado = true;
            linha = key + valor;
        }
        if(saida == null)
        {
            saida = linha;
        }
        else
        {
            saida += "\n"+linha;
        }
    }
    //se não exitir nenhum parametro com essa key ele adiciona um novo;
    if(!encontrado)
    {
        saida += "\n"+key+valor;
    }
    return saida;
}

If you want to record objects with various parameters it may be interesting to take a look at serializable that he does all the heavy lifting for you...

  • That’s what I had thought to do, but it would be a lot of work, so I did a trick, because there are very few strings I need to record, will be at most 5.. So I created a folder and a file for each one, containing its value only

Browser other questions tagged

You are not signed in. Login or sign up in order to post.