Handle files with C#

Asked

Viewed 1,008 times

2

The goal is to capture two string typed into two blocks of text and saved them in a file (this file is already predefined and the user will not know where it is). I also want to know how I read the file information and store this information in strings.

File example:

    Nome: Leonardo
    Sobrenome: Vilarinho

The name and surname is what the user will type in the text blocks, and is what I should put in the file, but I should also access this information later and store it in strings, example, store "Leonardo" in a string name and "Vilarinho" in a string surname. And whenever the user puts another name or surname in the text block he replaces the file.

The file is inside the Visual Studio project, if possible, how to encrypt the file after it is saved. I have tried using File library IO, but I don’t know much about it.

I tried so:

File.Open(dados.txt, FileMode TextWriter);
 File.WriteAllText("Nome: %s\nSobrenome: %s", usuario, sobrenome );

But as you can see, I don’t know anything about files, and the code is all wrong, I’ve seen a lot of videos, but none like my goal. I didn’t even try to get the file information later, since I couldn’t even save it.

1 answer

1


Take a closer look at the documentation of MSDN, the method .WriteAllText does not work the way you are trying to do. The first parameter is the location of the file and the second the content.

var conteudo = string.Format("Nome: {0}{1}Sobrenome: {2}", usuario, Environment.NewLine, sobrenome);
var caminho = @"C://seudiretorio/meuarquivo.txt";

File.WriteAllText(caminho, conteudo);

To read use the Streamreader:

StreamReader file = new StreamReader(caminho);
while ((line = file.ReadLine()) != null)
{
   if (line.Contains("Nome:"))
      usuario = line.Replace("Nome:","").Trim();
   else if (line.Contains("Sobrenome:"))
      sobrenome = line.Replace("Sobrenome:","").Trim();
}
file.Close();

About encryption I suggest you read this here first: What’s the difference between Encoding, Encryption and Hashing?

  • @Leonardovilarinho string :)

  • 1

    I got it here, thank you, well written code made it all clear. And it worked, now I’ll see the encryption thingy

  • To encrypt I used this video https://www.youtube.com/watch?v=PxQbu65xt7Q

  • @Leonardovilarinho cool video :)

Browser other questions tagged

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