Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lectura de Archivos utilizando StreamReader | Additional Structures & File Handling
C# Beyond Basics

Lectura de Archivos utilizando StreamReaderLectura de Archivos utilizando StreamReader

Podemos abrir y leer archivos utilizando el lenguaje de programación C#.

Para leer un archivo, creamos un nuevo objeto StreamReader. El StreamReader objeto toma en la ruta del archivo.

Nota

El término "objeto" será más claro en las secciones posteriores, sin embargo, a efectos de comprensión - un objeto es simplemente una instancia de un tipo de datos, y StreamReader es un tipo de datos como int o float. Así que los valores 1, 2.5f y "Hola Mundo" pueden ser técnicamente referidos como "objetos" de los tipos de datos int, float y string respectivamente.

Aquí fileVarName representa el nombre de la variable en la que almacenaremos el objeto StreamReader, y fullPath se supone que es la ruta completa del fichero en forma de cadena.

Por ejemplo, queremos abrir un fichero "text.txt" en el Escritorio que tiene la ruta C:/Usuarios/Admin/Desktop/text.txt:

Nota

También podemos utilizar la declaración implícita para hacer la sintaxis ligeramente más corta: `var textFile = new StreamReader("C:/Usuarios/Administradores/Escritorio/text.txt");``

Consideremos que el fichero text.txt tiene el siguiente contenido:

Un objeto StreamReader tiene un método ReadLine que lee una línea del fichero y la devuelve:

Salida:

El método ReadLine cambia automáticamente el cursor a la siguiente línea, por lo que cuando se llama de nuevo, lee la siguiente línea si la hay, de lo contrario simplemente devuelve null (nada):

Salida:

Para leer todas las líneas de un fichero podemos utilizar el bucle while con una condición que compruebe si la siguiente línea es null o no. A continuación se muestra una forma sencilla de hacerlo:

Salida:

Podemos hacer el código anterior un poco más ordenado usando un truco, para ello echemos un vistazo a las signaciones. Una sentencia assignment tiene también un valor de retorno, que es el valor que se asigna. Se puede entender con un ejemplo:

Salida:

La salida es 7 porque la sentencia a = 7 devuelve 7 que es el valor asignado a a.

Podemos usar esta información para hacer algunas cosas creativas como asignar el mismo valor a múltiples variables en una sola sentencia:

Salida:

Usando esta información, podemos modificar el código de lectura del fichero para hacerlo más corto eliminando código innecesario:

Dentro de la condición utilizamos primero una sentencia de asignación line = textFile.ReadLine() que actualiza automáticamente la variable line y luego comprueba si es nula a partir del valor de retorno de la sentencia.

Después de leer el archivo también debemos cerrarlo utilizando el método Close, de lo contrario puede potencialmente causar fugas de memoria o el archivo puede ser bloqueado y ser inaccesible desde otros lugares, siempre y cuando el programa se está ejecutando.

El código final será algo como esto

The term "object" will become more clear in the later sections however for understanding purposes - an object is simply an instance of a data type, and StreamReader is a data type just like int or float. So the values 1, 2.5f and "Hello World" can be technically referred to as "objects" of the int, float and string data types respectively.
cs

index.cs

Here fileVarName represents the variable name in which we will store the StreamReader object, and fullPath is supposed to be the full path of the file in the form of a string.

For-example we want to open a file "text.txt" on Desktop which has the path C:/Users/Admin/Desktop/text.txt:

cs

index.cs

We can also use implicit declaration to make the syntax slightly shorter: var textFile = new StreamReader("C:/Users/Admin/Desktop/text.txt");

Consider the text.txt file has the following content:

txt

text.txt

A StreamReader object has a ReadLine method which reads one line from the file and returns it:

cs

index.cs

Output:

The ReadLine method automatically switches the cursor to the next line so when it's called again, it reads the next line if there is any, otherwise it simply returns null (nothing):

Output:

For reading all the lines from a file we can use the while loop with a condition which checks if the next line is null or not. Following is a simple way we can do that:

Output:

We can make the above code a bit neater using a trick, for that lets take a look at the assignment statements. An assignment statement has a return value as well, which is the value that is being assigned. It can be understood with an example:

Output:

It outputs 7 because the statement a = 7 returns 7 which is the value being assigned to a.

We can use this information to do some creative things like assigning the same value to multiple variables in a single statement:

Output:

Using this information, we can modify the file reading code to make it shorter removing unnecessary code:

Inside the condition we first used an assignment statement line = textFile.ReadLine() which automatically updates the line variable and then checks if it's null from the statement's return value.

After reading the file we must also close it using the Close method, otherwise it can potentially cause memory leaks or the file can be locked and become inaccessible from other places as long as the program is running.

The final code will look something like this:

The ReadLine method automatically switches the cursor to the next line so when it's called again, it reads the next line if there is any, otherwise it simply returns null (nothing):

cs

index.cs

Output:

For reading all the lines from a file we can use the while loop with a condition which checks if the next line is null or not. Following is a simple way we can do that:

cs

index.cs

Output:

We can make the above code a bit neater using a trick, for that lets take a look at the assignment statements. An assignment statement has a return value as well, which is the value that is being assigned. It can be understood with an example:

cs

index.cs

Output:

It outputs 7 because the statement a = 7 returns 7 which is the value being assigned to a.

We can use this information to do some creative things like assigning the same value to multiple variables in a single statement:

cs

index.cs

Output:

Using this information, we can modify the file reading code to make it shorter removing unnecessary code:

cs

index.cs

Inside the condition we first used an assignment statement line = textFile.ReadLine() which automatically updates the line variable and then checks if it's null from the statement's return value.

After reading the file we must also close it using the Close method, otherwise it can potentially cause memory leaks or the file can be locked and become inaccessible from other places as long as the program is running.

The final code will look something like this:

cs

index.cs

question-icon

=();

Click or drag`n`drop items and fill in the blanks

¿Todo estuvo claro?

Sección 1. Capítulo 6
course content

Contenido del Curso

C# Beyond Basics

Lectura de Archivos utilizando StreamReaderLectura de Archivos utilizando StreamReader

Podemos abrir y leer archivos utilizando el lenguaje de programación C#.

Para leer un archivo, creamos un nuevo objeto StreamReader. El StreamReader objeto toma en la ruta del archivo.

Nota

El término "objeto" será más claro en las secciones posteriores, sin embargo, a efectos de comprensión - un objeto es simplemente una instancia de un tipo de datos, y StreamReader es un tipo de datos como int o float. Así que los valores 1, 2.5f y "Hola Mundo" pueden ser técnicamente referidos como "objetos" de los tipos de datos int, float y string respectivamente.

Aquí fileVarName representa el nombre de la variable en la que almacenaremos el objeto StreamReader, y fullPath se supone que es la ruta completa del fichero en forma de cadena.

Por ejemplo, queremos abrir un fichero "text.txt" en el Escritorio que tiene la ruta C:/Usuarios/Admin/Desktop/text.txt:

Nota

También podemos utilizar la declaración implícita para hacer la sintaxis ligeramente más corta: `var textFile = new StreamReader("C:/Usuarios/Administradores/Escritorio/text.txt");``

Consideremos que el fichero text.txt tiene el siguiente contenido:

Un objeto StreamReader tiene un método ReadLine que lee una línea del fichero y la devuelve:

Salida:

El método ReadLine cambia automáticamente el cursor a la siguiente línea, por lo que cuando se llama de nuevo, lee la siguiente línea si la hay, de lo contrario simplemente devuelve null (nada):

Salida:

Para leer todas las líneas de un fichero podemos utilizar el bucle while con una condición que compruebe si la siguiente línea es null o no. A continuación se muestra una forma sencilla de hacerlo:

Salida:

Podemos hacer el código anterior un poco más ordenado usando un truco, para ello echemos un vistazo a las signaciones. Una sentencia assignment tiene también un valor de retorno, que es el valor que se asigna. Se puede entender con un ejemplo:

Salida:

La salida es 7 porque la sentencia a = 7 devuelve 7 que es el valor asignado a a.

Podemos usar esta información para hacer algunas cosas creativas como asignar el mismo valor a múltiples variables en una sola sentencia:

Salida:

Usando esta información, podemos modificar el código de lectura del fichero para hacerlo más corto eliminando código innecesario:

Dentro de la condición utilizamos primero una sentencia de asignación line = textFile.ReadLine() que actualiza automáticamente la variable line y luego comprueba si es nula a partir del valor de retorno de la sentencia.

Después de leer el archivo también debemos cerrarlo utilizando el método Close, de lo contrario puede potencialmente causar fugas de memoria o el archivo puede ser bloqueado y ser inaccesible desde otros lugares, siempre y cuando el programa se está ejecutando.

El código final será algo como esto

The term "object" will become more clear in the later sections however for understanding purposes - an object is simply an instance of a data type, and StreamReader is a data type just like int or float. So the values 1, 2.5f and "Hello World" can be technically referred to as "objects" of the int, float and string data types respectively.
cs

index.cs

Here fileVarName represents the variable name in which we will store the StreamReader object, and fullPath is supposed to be the full path of the file in the form of a string.

For-example we want to open a file "text.txt" on Desktop which has the path C:/Users/Admin/Desktop/text.txt:

cs

index.cs

We can also use implicit declaration to make the syntax slightly shorter: var textFile = new StreamReader("C:/Users/Admin/Desktop/text.txt");

Consider the text.txt file has the following content:

txt

text.txt

A StreamReader object has a ReadLine method which reads one line from the file and returns it:

cs

index.cs

Output:

The ReadLine method automatically switches the cursor to the next line so when it's called again, it reads the next line if there is any, otherwise it simply returns null (nothing):

Output:

For reading all the lines from a file we can use the while loop with a condition which checks if the next line is null or not. Following is a simple way we can do that:

Output:

We can make the above code a bit neater using a trick, for that lets take a look at the assignment statements. An assignment statement has a return value as well, which is the value that is being assigned. It can be understood with an example:

Output:

It outputs 7 because the statement a = 7 returns 7 which is the value being assigned to a.

We can use this information to do some creative things like assigning the same value to multiple variables in a single statement:

Output:

Using this information, we can modify the file reading code to make it shorter removing unnecessary code:

Inside the condition we first used an assignment statement line = textFile.ReadLine() which automatically updates the line variable and then checks if it's null from the statement's return value.

After reading the file we must also close it using the Close method, otherwise it can potentially cause memory leaks or the file can be locked and become inaccessible from other places as long as the program is running.

The final code will look something like this:

The ReadLine method automatically switches the cursor to the next line so when it's called again, it reads the next line if there is any, otherwise it simply returns null (nothing):

cs

index.cs

Output:

For reading all the lines from a file we can use the while loop with a condition which checks if the next line is null or not. Following is a simple way we can do that:

cs

index.cs

Output:

We can make the above code a bit neater using a trick, for that lets take a look at the assignment statements. An assignment statement has a return value as well, which is the value that is being assigned. It can be understood with an example:

cs

index.cs

Output:

It outputs 7 because the statement a = 7 returns 7 which is the value being assigned to a.

We can use this information to do some creative things like assigning the same value to multiple variables in a single statement:

cs

index.cs

Output:

Using this information, we can modify the file reading code to make it shorter removing unnecessary code:

cs

index.cs

Inside the condition we first used an assignment statement line = textFile.ReadLine() which automatically updates the line variable and then checks if it's null from the statement's return value.

After reading the file we must also close it using the Close method, otherwise it can potentially cause memory leaks or the file can be locked and become inaccessible from other places as long as the program is running.

The final code will look something like this:

cs

index.cs

question-icon

=();

Click or drag`n`drop items and fill in the blanks

¿Todo estuvo claro?

Sección 1. Capítulo 6
some-alt