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

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 got 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 to the file I'm using different parameters, such as a key to identify what I'm writing, such 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: You are always recording on the first line of the file, and erasing the other one I had written, I want to know how to write content in an empty line of the file without deleting the file all, and if you already have a line of the parameter c1- or c2- (cor1 and cor2) it will replace the existing line by changing only the value after -

    
asked by anonymous 20.09.2015 / 00:20

1 answer

1

File.WriteAllText Method (String, String)

  

Creates a new file, writes the string specified in 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 saving all the data in your file to a string, modify it as you want 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 write objects with multiple parameters, it might be interesting to take a look at serializable that it does all the heavy lifting for you ...

    
20.09.2015 / 04:13