Reading text files in Textbox

1

I am looking forward to working on my applications with simple text files. Something very simple, place a button and a TextBox .

The TextBox will show the content of the .txt and the button will give the instruction to load it.

I work with Visual Studio and with the C # language.

Now, I managed to do this that I have the following code:

private void btnShowTxt_Click(object sender, EventArgs e)
{
  string texto = File.ReadAllText("test.txt");
  txtShowTxt.Text = texto;
}

The problem is that I noticed that if the test.txt file is not found in the path specified by Visual Studio, it generates an exception. What I want is that, whoever has my application, can read from the path that I place in the code, load in TextBox the content of the text file.

For example, the user places the file "test.txt" in Documents or moves it to Desktop, it does not matter. I do not know why Visual Studio generates the exception if the file is not found inside the project folder.

    
asked by Fernando Valdata 18.12.2017 в 23:50
source

2 answers

1

I think I can not understand the need, but without a doubt the first thing that is required is to validate if the file exists in the specified route using the method File.Exists so that it does not generate any exception:

using System.IO;
private void btnShowTxt_Click(object sender, EventArgs e)
{
    string texto = string.Empty;
    string path = "c:\temp\test.txt";

    if(File.Exists(path))
        texto = File.ReadAllText(path);
    else
        texto = "Archivo no encontrado";

    txtShowTxt.Text = texto;
}

As such, Visual Studio or the type of solution you use (console, desktop, web, etc.) does not have the functionality to detect if a file has changed its route, and in this case you should specify it to validate if the file exists or not.

    
answered by 20.12.2017 / 09:40
source
1

The language (like practically everyone) searches for the file where you tell it to look for it. In this case, if you tell him to open a file that is in the project's folder, the language will look for the file there and open it. If it is not, it will throw an exception.

If you want the program to open a file from the desktop, you must give the full path to the desktop; for example: File.ReadAllText("C:\Usuarios\User\Desktop\test.txt"); .

Obviously, doing it that way is not ideal, because the route can vary between computers. In that case, the program should be extended so that the user enters the path of his file (either by writing it or by using a file selection window), so that the program uses that path entered by the user to search for the file there.

    
answered by 19.12.2017 в 02:17