Item (Int32)
.NET Framework (current version)
Otras versiones
Sintaxis
C#
C++
F#
VB
public T this[
int index
] { get; set; }
Parámetros
index
Type: System.Int32
Valor de propiedad
Type: T
Implementa
IList<T>.Item[Int32] IReadOnlyList<T>.Item[Int32]
Excepciones
Exception Condition
index es menor que 0.
ArgumentOutOfRangeException O bien
Comentarios
List<T> acepta null como un valor válido para la referencia de tipos y permite elementos
duplicados.
Recuperación del valor de esta propiedad es una operación o (1); establecer la propiedad
también es una operación o (1).
Ejemplos
El ejemplo de esta sección muestra el Item propiedad (el indizador en C#) y varias otras
propiedades y métodos de la List<T> clase genérica. Después de la lista crean y rellenan
con el Add (método), un elemento se recupera y se muestra mediante el Item propiedad.
(Para obtener un ejemplo que utiliza el Item propiedad para establecer el valor de un
elemento de lista, consulte AsReadOnly.)
Nota
Visual Basic, C# y C++ todos tienen sintaxis para tener acceso a la Item propiedad sin
utilizar su nombre. En su lugar, la variable que contiene el List<T> se utiliza como si fuera
una matriz.
El lenguaje C# utiliza la palabra clave para definir los indizadores en lugar de implementar
la Item propiedad. Visual Basic implementa Item como propiedad predeterminada, lo que
proporciona la misma funcionalidad de indización.
C#
VB
List<string> dinosaurs = new List<string>();
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
C#
VB
// Shows accessing the list using the Item property.
Console.WriteLine("\ndinosaurs[3]: {0}", dinosaurs[3]);
Sintaxis
C#
C++
F#
VB
public void Insert(
int index,
T item
)
Parámetros
index
Type: System.Int32
item
Type: T
Objeto que se va a insertar. El valor puede ser null para los tipos de referencia.
Implementa
IList<T>.Insert(Int32, T)
Excepciones
Exception Condition
Comentarios
List<T> acepta null como un valor válido para la referencia de tipos y permite elementos
duplicados.
Ejemplos
En el ejemplo siguiente se muestra cómo agregar, quitar e insertar un objeto comercial
simple en un List<T>.
C#
F#
VB
using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
public class Part : IEquatable<Part>
{
public string PartName { get; set; }
}
public class Example
{
public static void Main()
{
// Create a list of parts.
List<Part> parts = new List<Part>();
// Write out the parts in the list. This will call the overridden ToString method
// in the Part class.
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// Check the list for part #1734. This calls the IEquitable.Equals method
// of the Part class, which checks the PartId for equality.
Console.WriteLine("\nContains(\"1734\"): {0}",
parts.Contains(new Part {PartId=1734, PartName="" }));
Console.WriteLine("\nRemove(\"1534\")");
// This will remove part 1534 even though the PartName is different,
// because the Equals method only checks PartId for equality.
parts.Remove(new Part(){PartId=1534, PartName="cogs"});
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
Console.WriteLine("\nRemoveAt(3)");
// This will remove the part at index 3.
parts.RemoveAt(3);
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
/*
Contains("1734"): False
Insert(2, "1834")
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1534 Name: cassette
ID: 1634 Name: shift lever
Remove("1534")
RemoveAt(3)
*/
}
}
En el ejemplo siguiente se muestra el Insert método, junto con otras propiedades y métodos
de la List<T> clase genérica. Después de crea la lista, se agregan elementos. El Insert
método se utiliza para insertar un elemento en la mitad de la lista. El elemento insertado es
un duplicado, que se quita posteriormente utilizando el Remove método.
C#
C++
F#
VB
using System;
using System.Collections.Generic;
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nCapacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
dinosaurs.Contains("Deinonychus"));
Console.WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs.Insert(2, "Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs.Remove("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
}
}
Capacity: 0
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
Capacity: 8
Count: 5
Contains("Deinonychus"): True
Insert(2, "Compsognathus")
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
dinosaurs[3]: Mamenchisaurus
Remove("Compsognathus")
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
TrimExcess()
Capacity: 5
Count: 5
Clear()
Capacity: 5
Count: 0
*/
Sintaxis
C#
C++
F#
VB
public bool Remove(
T item
)
Parámetros
item
Type: T
Objeto que se va a quitar de List<T>. El valor puede ser null para los tipos de
referencia.
Valor devuelto
Type: System.Boolean
Es true si item se quita correctamente; en caso contrario, es false. Este método también
devuelve false si no se encuentra item en List<T>.
Implementa
ICollection<T>.Remove(T)
Comentarios
Si tipo T implementa el IEquatable<T> interfaz genérica, el comparador de igualdad es el
Equals método de dicha interfaz; en caso contrario, el comparador de igualdad
predeterminado es Object.Equals.
Este método realiza una búsqueda lineal; por lo tanto, este método es una O (n) operación,
donde n es Count.
Ejemplos
En el ejemplo siguiente se muestra cómo agregar, quitar e insertar un objeto comercial
simple en un List<T>.
C#
F#
VB
using System;
using System.Collections.Generic;
// Simple business object. A PartId is used to identify the type of part
// but the part name can change.
public class Part : IEquatable<Part>
{
public string PartName { get; set; }
}
public class Example
{
public static void Main()
{
// Create a list of parts.
List<Part> parts = new List<Part>();
// Write out the parts in the list. This will call the overridden ToString method
// in the Part class.
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
// Check the list for part #1734. This calls the IEquitable.Equals method
// of the Part class, which checks the PartId for equality.
Console.WriteLine("\nContains(\"1734\"): {0}",
parts.Contains(new Part {PartId=1734, PartName="" }));
//Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
Console.WriteLine("\nRemove(\"1534\")");
// This will remove part 1534 even though the PartName is different,
// because the Equals method only checks PartId for equality.
parts.Remove(new Part(){PartId=1534, PartName="cogs"});
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
Console.WriteLine("\nRemoveAt(3)");
// This will remove the part at index 3.
parts.RemoveAt(3);
Console.WriteLine();
foreach (Part aPart in parts)
{
Console.WriteLine(aPart);
}
/*
Contains("1734"): False
Insert(2, "1834")
ID: 1234 Name: crank arm
ID: 1334 Name: chain ring
ID: 1834 Name: brake lever
ID: 1434 Name: regular seat
ID: 1444 Name: banana seat
ID: 1534 Name: cassette
ID: 1634 Name: shift lever
Remove("1534")
*/
}
}
C#
C++
F#
VB
using System;
using System.Collections.Generic;
dinosaurs.Add("Tyrannosaurus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Mamenchisaurus");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nContains(\"Deinonychus\"): {0}",
dinosaurs.Contains("Deinonychus"));
Console.WriteLine("\nInsert(2, \"Compsognathus\")");
dinosaurs.Insert(2, "Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nRemove(\"Compsognathus\")");
dinosaurs.Remove("Compsognathus");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
dinosaurs.TrimExcess();
Console.WriteLine("\nTrimExcess()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
dinosaurs.Clear();
Console.WriteLine("\nClear()");
Console.WriteLine("Capacity: {0}", dinosaurs.Capacity);
Console.WriteLine("Count: {0}", dinosaurs.Count);
}
}
Capacity: 0
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
Capacity: 8
Count: 5
Contains("Deinonychus"): True
Insert(2, "Compsognathus")
Tyrannosaurus
Amargasaurus
Compsognathus
Mamenchisaurus
Deinonychus
Compsognathus
dinosaurs[3]: Mamenchisaurus
Remove("Compsognathus")
Tyrannosaurus
Amargasaurus
Mamenchisaurus
Deinonychus
Compsognathus
TrimExcess()
Capacity: 5
Count: 5
Clear()
Capacity: 5
Count: 0
*/
Método List<T>.RemoveAll
(Predicate<T>)
Quita todos los elementos que cumplen las condiciones definidas por el predicado
especificado.
Sintaxis
C#
public int RemoveAll(
Predicate<T> match
)
Parámetros
match
Type: System.Predicate<T>
Delegado Predicate<T> que define las condiciones de los elementos que se van a
quitar.
Valor devuelto
Type: System.Int32
Número de elementos que se han quitado de List<T> .
Excepciones
Exception Condition
Comentarios
El Predicate<T> es un delegado a un método que devuelve true Si el objeto pasa a coincide
con las condiciones definidas en el delegado. Los elementos de la actual List<T> se pasan
individualmente a la Predicate<T> delegado y los elementos que cumplen las condiciones
se quitan de la List<T>.
Este método realiza una búsqueda lineal; por lo tanto, este método es una O (n) operación,
donde n es Count.
Ejemplos
En el ejemplo siguiente se muestra el RemoveAll (método) y otros métodos que utilizan el
Predicate<T> delegado genérico.
Un List<T> de cadenas se crea, que contiene 8 nombres de dinosaurios, dos de los cuales
(en las posiciones 1 y 5) terminan en "saurus". El ejemplo también define un método de
predicado de búsqueda denominado EndsWithSaurus, que acepta un parámetro de cadena y
devuelve un valor booleano de valor que indica si la cadena de entrada termina en "saurus".
El Find, FindLast, y FindAll métodos se usan para buscar en la lista con el método de
predicado de búsqueda.
El RemoveAll método se utiliza para quitar todas las entradas que terminan en "saurus".
Recorre la lista desde el principio, pasando cada elemento a su vez a la EndsWithSaurus
(método). El elemento se quita si el EndsWithSaurus método devuelve true.
Nota
Por último, el Exists método comprueba que no hay ninguna cadena de la lista que terminan
en "saurus".
C#
C++
VB
using System;
using System.Collections.Generic;
dinosaurs.Add("Compsognathus");
dinosaurs.Add("Amargasaurus");
dinosaurs.Add("Oviraptor");
dinosaurs.Add("Velociraptor");
dinosaurs.Add("Deinonychus");
dinosaurs.Add("Dilophosaurus");
dinosaurs.Add("Gallimimus");
dinosaurs.Add("Triceratops");
Console.WriteLine();
foreach(string dinosaur in dinosaurs)
{
Console.WriteLine(dinosaur);
}
Console.WriteLine("\nTrueForAll(EndsWithSaurus): {0}",
dinosaurs.TrueForAll(EndsWithSaurus));
Console.WriteLine("\nFind(EndsWithSaurus): {0}",
dinosaurs.Find(EndsWithSaurus));
Console.WriteLine("\nFindLast(EndsWithSaurus): {0}",
dinosaurs.FindLast(EndsWithSaurus));
Console.WriteLine("\nFindAll(EndsWithSaurus):");
List<string> sublist = dinosaurs.FindAll(EndsWithSaurus);
Console.WriteLine(
"\n{0} elements removed by RemoveAll(EndsWithSaurus).",
dinosaurs.RemoveAll(EndsWithSaurus));
Compsognathus
Amargasaurus
Oviraptor
Velociraptor
Deinonychus
Dilophosaurus
Gallimimus
Triceratops
TrueForAll(EndsWithSaurus): False
Find(EndsWithSaurus): Amargasaurus
FindLast(EndsWithSaurus): Dilophosaurus
FindAll(EndsWithSaurus):
Amargasaurus
Dilophosaurus
Exists(EndsWithSaurus): False
*/
ARCHIVOS DE TEXTO
RESUMEN
Requisitos
Leer y escribir archivos de texto
o Leer un archivo de texto
o Escribir un archivo de texto (ejemplo 1)
o Escribir un archivo de texto (ejemplo 2)
Lista de código completa
Solucionar problemas
REFERENCIAS
Resumen
En este artículo paso a paso describe cómo leer y escribir en un archivo de texto mediante Visual
C#.
Requisitos
La lista siguiente describe el hardware recomendado, software, infraestructura de red y los service
packs que debe tener:
Visual C#
La sección de un archivo de texto de lectura de este artículo describe cómo utilizar la clase
StreamReader para leer un archivo de texto. Escribir un archivo de texto (ejemplo 1) y el
Escribir un archivo de texto (ejemplo 2) secciones describen cómo utilizar la clase StreamWriter
para escribir texto en un archivo.
Leer un archivo de texto
El siguiente código utiliza la clase StreamReader para abrir, leer y cerrar el archivo de texto. La ruta
de acceso de un archivo de texto puede pasar al constructor StreamReader para abrir el archivo
automáticamente. El método ReadLine lee cada línea de texto e incrementa el puntero de archivo a
la siguiente línea como lo lee. Cuando el método ReadLine alcanza el final del archivo, devuelve
una referencia nula.
1. Crear un archivo de texto de ejemplo en el Bloc de notas. Para ello, siga estos pasos:
1. En el Bloc de notas, pegue el texto siguiente:
hello world
Nota: En Visual Studio 2005 o Visual Studio 2008, haga clic en Visual C# en Tipos de
proyecto y, a continuación, haga clic en Aplicación de consola en plantillas.
5. Agregue el código siguiente al principio del archivo Class1.cs:
using System.IO;
String line;try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");
Hello world
Escribir un archivo de texto (ejemplo 1)
El siguiente código utiliza la clase StreamWriter para abrir, escribir y cerrar el archivo de texto. De
forma similar a la clase StreamReader, puede pasar la ruta de acceso de un archivo de texto al
constructor StreamWriter para abrir el archivo automáticamente. El método WriteLine escribe una
línea completa de texto en el archivo de texto.
Nota: En Visual Studio 2005 o Visual Studio 2008, haga clic en Visual C# en Tipos de
proyectoy, a continuación, haga clic en Aplicación de consola CLR en plantillas.
4. Agregue el código siguiente al principio del archivo Class1.cs:
using System.IO;
try {
6. En el menú Depurar, haga clic en Iniciar para compilar y ejecutar la aplicación. Este
código crea un archivo denominado Test.txt en la unidad C. abrir Test.txt en un editor de
texto como el Bloc de notas. Test.txt contiene dos líneas de texto:
ASC11
Unicode
UTF7
UTF8
El método Write es similar al método WriteLine, excepto que el método Write no incrusta
automáticamente un retorno de carro o salto de línea de combinación de caracteres (CR/LF). Esto es
útil cuando desea escribir un carácter a la vez.
Nota: En Visual Studio 2005 o Visual Studio 2008, haga clic en Visual C# en Tipos de
proyectoy, a continuación, haga clic en Aplicación de consola en plantillas
4. Al principio del archivo Class1.cs, agregue el código siguiente:
Int64 x;
try
{
//Open the File
StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
0123456789
Volver al principio
Lista de código completa
namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
String line;
try
{
//Pass the file path and file name to the StreamReader constructor
StreamReader sr = new StreamReader("C:\\Sample.txt");
namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
try
{
namespace readwriteapp
{
class Class1
{
[STAThread]
static void Main(string[] args)
{
Int64 x;
try
{
//Open the File
StreamWriter sw = new StreamWriter("C:\\Test1.txt", true, Encoding.ASCII);
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Imports Microsoft.VisualBasic
Class DirAppend
Public Shared Sub Main()
Dim w As StreamWriter = File.AppendText("log.txt")
Log("Test1", w)
Log("Test2", w)
' Close the writer and underlying file.
w.Close()
' Open and read the file.
Dim r As StreamReader = File.OpenText("log.txt")
DumpLog(r)
End Sub
Public Shared Sub Log(ByVal logMessage As String, ByVal w As
TextWriter)
w.Write(ControlChars.CrLf & "Log Entry : ")
w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString())
w.WriteLine(" :")
w.WriteLine(" :{0}", logMessage)
w.WriteLine("-------------------------------")
' Update the underlying file.
w.Flush()
End Sub
Public Shared Sub DumpLog(ByVal r As StreamReader)
' While not at the end of the file, read and write lines.
Dim line As String
line = r.ReadLine()
While Not line Is Nothing
Console.WriteLine(line)
line = r.ReadLine()
End While
r.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
class DirAppend
{
public static void Main(String[] args)
{
StreamWriter w = File.AppendText("log.txt");
Log ("Test1", w);
Log ("Test2", w);
// Close the writer and underlying file.
w.Close();
// Open and read the file.
StreamReader r = File.OpenText("log.txt");
DumpLog (r);
}
public static void Log (String logMessage, TextWriter w)
{
w.Write("\r\nLog Entry : ");
w.WriteLine("{0} {1}", DateTime.Now.ToLongTimeString(),
DateTime.Now.ToLongDateString());
w.WriteLine(" :");
w.WriteLine(" :{0}", logMessage);
w.WriteLine ("-------------------------------");
// Update the underlying file.
w.Flush();
}
public static void DumpLog (StreamReader r)
{
// While not at the end of the file, read and write lines.
String line;
while ((line=r.ReadLine())!=null)
{
Console.WriteLine(line);
}
r.Close();
}
}
Leer y escribir en un archivo de datos
recién creado
.NET Framework 1.1
Las clases BinaryWriter y BinaryReader se usan para escribir y leer datos, en lugar de
cadenas de caracteres. En el siguiente ejemplo de código se muestra cómo se escriben y se
leen datos en una nueva secuencia de archivos vacía (Test.data). Después de crear el
archivo de datos en el directorio actual, se crean las clases BinaryWriter y BinaryReader
asociadas, y BinaryWriter se usa para escribir los enteros de 0 a 10 en Test.data, que
deja el puntero de archivo al final del archivo. Después de volver a establecer el puntero de
archivo en el origen, BinaryReader lee el contenido especificado.
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Class MyStream
Private Const FILE_NAME As String = "Test.data"
Public Shared Sub Main()
' Create the new, empty data file.
If File.Exists(FILE_NAME) Then
Console.WriteLine("{0} already exists!", FILE_NAME)
Return
End If
Dim fs As New FileStream(FILE_NAME, FileMode.CreateNew)
' Create the writer for data.
Dim w As New BinaryWriter(fs)
' Write data to Test.data.
Dim i As Integer
For i = 0 To 10
w.Write(CInt(i))
Next i
w.Close()
fs.Close()
' Create the reader for data.
fs = New FileStream(FILE_NAME, FileMode.Open, FileAccess.Read)
Dim r As New BinaryReader(fs)
' Read data from Test.data.
For i = 0 To 10
Console.WriteLine(r.ReadInt32())
Next i
w.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
class MyStream
{
private const string FILE_NAME = "Test.data";
public static void Main(String[] args)
{
// Create the new, empty data file.
if (File.Exists(FILE_NAME))
{
Console.WriteLine("{0} already exists!", FILE_NAME);
return;
}
FileStream fs = new FileStream(FILE_NAME, FileMode.CreateNew);
// Create the writer for data.
BinaryWriter w = new BinaryWriter(fs);
// Write data to Test.data.
for (int i = 0; i < 11; i++)
{
w.Write( (int) i);
}
w.Close();
fs.Close();
// Create the reader for data.
fs = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
// Read data from Test.data.
for (int i = 0; i < 11; i++)
{
Console.WriteLine(r.ReadInt32());
}
w.Close();
}
}
En el siguiente ejemplo de código se muestra la forma de utilizar las clases de E/S para
crear un listado de directorio.
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Class DirectoryLister
Public Shared Sub Main()
Dim dir As New DirectoryInfo(".")
Dim f As FileInfo
For Each f In dir.GetFiles("*.cs")
Dim name As [String] = f.FullName
Dim size As Long = f.Length
Dim creationTime As DateTime = f.CreationTime
Console.WriteLine("{0,-12:N0} {1,-20:g} {2}", size,
creationTime, name)
Next f
End Sub
End Class
[C#]
using System;
using System.IO;
class DirectoryLister
{
public static void Main(String[] args)
{
DirectoryInfo dir = new DirectoryInfo(".");
foreach (FileInfo f in dir.GetFiles("*.cs"))
{
String name = f.FullName;
long size = f.Length;
DateTime creationTime = f.CreationTime;
Console.WriteLine("{0,-12:N0} {1,-20:g} {2}", size,
creationTime, name);
}
}
}
Si se desea una lista de los archivos de otro directorio, como el directorio raíz C:\, se debe
usar la barra diagonal inversa (\) como carácter de escape, como en "C:\\". También se
pueden usar caracteres de barra del tipo Unix, como en "C:/".
VB
Imports System
Imports System.IO
Class Test
Public Shared Sub Main()
Try
' Create an instance of StreamReader to read from a file.
Dim sr As StreamReader = New StreamReader("TestFile.txt")
Dim line As String
' Read and display the lines from the file until the end
' of the file is reached.
Do
line = sr.ReadLine()
Console.WriteLine(Line)
Loop Until line Is Nothing
sr.Close()
Catch E As Exception
' Let the user know what went wrong.
Console.WriteLine("The file could not be read:")
Console.WriteLine(E.Message)
End Try
End Sub
End Class
[C#]
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(e.Message);
}
}
}
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Public Class TextFromFile
Private Const FILE_NAME As String = "MyFile.txt"
Public Shared Sub Main()
If Not File.Exists(FILE_NAME) Then
Console.WriteLine("{0} does not exist.", FILE_NAME)
Return
End If
Dim sr As StreamReader = File.OpenText(FILE_NAME)
Dim input As String
input = sr.ReadLine()
While Not input Is Nothing
Console.WriteLine(input)
input = sr.ReadLine()
End While
Console.WriteLine("The end of the stream has been reached.")
sr.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
public class TextFromFile
{
private const string FILE_NAME = "MyFile.txt";
public static void Main(String[] args)
{
if (!File.Exists(FILE_NAME))
{
Console.WriteLine("{0} does not exist.", FILE_NAME);
return;
}
StreamReader sr = File.OpenText(FILE_NAME);
String input;
while ((input=sr.ReadLine())!=null)
{
Console.WriteLine(input);
}
Console.WriteLine ("The end of the stream has been reached.");
sr.Close();
}
}
Este código crea un StreamReader que selecciona MyFile.txt mediante una llamada a
File.OpenText. StreamReader.ReadLine devuelve cada línea como una cadena. Cuando ya
no hay más caracteres que leer, se muestra un mensaje que lo notifica y se cierra la
secuencia.
VB
Imports System
Imports System.IO
Class Test
Public Shared Sub Main()
' Create an instance of StreamWriter to write text to a file.
Dim sw As StreamWriter = New StreamWriter("TestFile.txt")
' Add some text to the file.
sw.Write("This is the ")
sw.WriteLine("header for the file.")
sw.WriteLine("-------------------")
' Arbitrary objects can also be written to the file.
sw.Write("The date is: ")
sw.WriteLine(DateTime.Now)
sw.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
class Test
{
public static void Main()
{
// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter("TestFile.txt"))
{
// Add some text to the file.
sw.Write("This is the ");
sw.WriteLine("header for the file.");
sw.WriteLine("-------------------");
// Arbitrary objects can also be written to the file.
sw.Write("The date is: ");
sw.WriteLine(DateTime.Now);
}
}
}
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Public Class TextToFile
Private Const FILE_NAME As String = "MyFile.txt"
Public Shared Sub Main()
If File.Exists(FILE_NAME) Then
Console.WriteLine("{0} already exists.", FILE_NAME)
Return
End If
Dim sr As StreamWriter = File.CreateText(FILE_NAME)
sr.WriteLine("This is my file.")
sr.WriteLine("I can write ints {0} or floats {1}, and so on.", 1,
4.2)
sr.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
public class TextToFile
{
private const string FILE_NAME = "MyFile.txt";
public static void Main(String[] args)
{
if (File.Exists(FILE_NAME))
{
Console.WriteLine("{0} already exists.", FILE_NAME);
return;
}
StreamWriter sr = File.CreateText(FILE_NAME);
sr.WriteLine ("This is my file.");
sr.WriteLine ("I can write ints {0} or floats {1}, and so on.",
1, 4.2);
sr.Close();
}
}
Este código define una cadena y la convierte en una matriz de caracteres, que se puede leer
usando el método StringReader.Read adecuado.
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Public Class CharsFromStr
Public Shared Sub Main()
' Create a string to read characters from.
Dim str As [String] = "Some number of characters"
' Size the array to hold all the characters of the string
' so that they are all accessible.
Dim b(24) As Char
' Create an instance of StringReader and attach it to the string.
Dim sr As New StringReader(str)
' Read 13 characters from the array that holds the string,
starting
' from the first array member.
sr.Read(b, 0, 13)
' Display the output.
Console.WriteLine(b)
' Close the StringReader.
sr.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
public class CharsFromStr
{
public static void Main(String[] args)
{
// Create a string to read characters from.
String str = "Some number of characters";
// Size the array to hold all the characters of the string
// so that they are all accessible.
char[] b = new char[24];
// Create an instance of StringReader and attach it to the
string.
StringReader sr = new StringReader(str);
// Read 13 characters from the array that holds the string,
starting
// from the first array member.
sr.Read(b, 0, 13);
// Display the output.
Console.WriteLine(b);
// Close the StringReader.
sr.Close();
}
}
Some number o
Escribir caracteres en una cadena
.NET Framework 1.1
VB
Option Explicit On
Option Strict On
Imports System
Imports System.IO
Imports System.Text
Public Class CharsToStr
Public Shared Sub Main()
' Create an instance of StringBuilder that can then be modified.
Dim sb As New StringBuilder("Some number of characters")
' Define and create an instance of a character array from which
' characters will be read into the StringBuilder.
Dim b As Char() = {" "c, "t"c, "o"c, " "c, "w"c, "r"c, "i"c,
"t"c, "e"c, " "c, "t"c, "o"c, "."c}
' Create an instance of StringWriter
' and attach it to the StringBuilder.
Dim sw As New StringWriter(sb)
' Write three characters from the array into the StringBuilder.
sw.Write(b, 0, 3)
' Display the output.
Console.WriteLine(sb)
' Close the StringWriter.
sw.Close()
End Sub
End Class
[C#]
using System;
using System.IO;
using System.Text;
Este ejemplo ilustra el uso de StringBuilder para modificar una cadena existente. Tenga en
cuenta que es necesaria una declaración using adicional, ya que la clase StringBuilder es
miembro del espacio de nombres System.Text. Además, en lugar de definir una cadena y
convertirla en matriz de caracteres, éste es un ejemplo de cómo crear una matriz de
caracteres directamente e inicializarla.
File : Contiene propiedad y metodos que tienen que ver con caracteristicas distintivas de los
archivos, para este post usaremo la clase File para abrir un archivo para sobreescritura
(Append) y para verificar la existencia de un archivo.
Verificando la Existencia
Dentro de la clase File, tenemos el metodo Exists(filename), que lleva como parametro el
nombre o ruta de un archivo, y como operacion revisa si este archivo existe. Para ilustrar un
ejemplo usaremos el siguiente trozo de codigo :
if(File.Exists("archivo.txt")){
// el archivo existe
}
else {
// el archivo no extiste
}
Dentro del if se verifica la existencia del archivo.txt, en caso de que el archivo exista se
inicia el bloque que sigue del if, en caso contrario (que no exista el archivo) se ejecuta el
bloque de codigo del else.
Leyendo Archivos
Dicho en la seccion de clases, la clase que usaremos para leer archivos sera StreamReader
veamos un ejemplo de lectura de archivo :
Este ejemplo de arriba es la clara seccion que lee un archivo llamado archivo.txt, veamos
unas secciones importantes.
Linea 1 : He aqui la creacion de la instancia de la clase StreamReader, al hacer new
StreamReader(filename) , donde filename es el nombre del archivo que deseamos abrir, en
este caso archivo.txt.
Linea 2 : Aqui leemos la primera linea del archivo con reader.ReadLine() y guardamos lo
leido en la variable read(string), recordando que reader es la variable de instancia de
StreamReader y ReadLine es el metodo (funcion dentro de la clase StreamReader) para leer
un linea del archivo.
Linea 4 : Escribimos en Consola el contenido de la variable read, que con tiene lo leido del
archivo y se actualiza con cada vuelta del ciclo.
Linea 7 : Cerramos el archivo, poner esta parte es muy importante, por que de lo contrario
si queremos usar el archivo en otra ocacion nos puede marcar error.
Una version un poco mas efectiva del algoritmo de leer el archivo seria, agregandole un
condicional inicial donde se verifique que el archivo en cuestion exista.
if(File.Exists("archivo.txt")){
StreamReader reader = new StreamReander("archivo.txt");
string read = reader.ReadLine();
while(read!=null){
Console.WriteLine(read);
read = reader.ReadLine();
}
reader.Close();
}
Escribiendo y Sobreescribiendo Archivos
*** Escribiendo ***
Linea 3 : Write hace la misma funcion que WriteLine, a diferencia de que Write no
escribe un fin de linea especifico.
Como vimos anteriormente el simple uso de StreamWriter, una vez que cerramos el archivo
y lo volvemos a abrir para escritura, este se iniciara a escribir de nuevo, el proceso de
sobreescritura significa seguir escribiendo debajo de los datos previamente guardados.
En diferencia al codigo de escritura, aqui solo hay una diferencia, que no usamos la
creacion de instancia para la clase StreamReader sino que usamos la clase File.
File.AppendText(filename), en filename va el nombre del archivo al cual queremos
sobreescribir…
Terminando
using System.IO;
using System;
mylogs.WriteLine(texto+ strDate);
mylogs.Close();
}
}
file.Close();
}
}
line = file.ReadToEnd();
Console.WriteLine(line);
file.close();
string LeerCSV()
{
byte Ncolumnas = 10; //DEFINIMOS LAS COLUMNAS QUE ACTUALIZAREMOS EN EL SERVER
string Tabla = "MI_TABLA_SQL";
string sentenciaSql= "";
string rutacompleta = @"D:\miArchivo.csv";
string datoIndividual;
try
{
//LEER LINEA POR LINEA EMPEZANDO DE LA 0 HASTA LA PENULTIMA
foreach (var linea in renglones)
{
//SEPARAR SEGÚN EL CARÁCTER "," Y ALMACENAR LOS DATOS EN UN ARRAY
Char delimiter = ',';
string[] datos = linea.Spliit(delimiter);
sentenciaSql="";
}
return "";
}
catch (Exception e)
{
return e.Message;
}
}