Cómo: Escribir texto en un archivo
En el ejemplo siguiente se muestra cómo escribir texto en un archivo de texto. Lee todos los archivos de texto de la carpeta Mis documentos del usuario mediante un modelo de búsqueda "*.txt" y los escribe en un archivo de texto grande.
![]() |
---|
Los usuarios de Visual Basic pueden optar por usar las propiedades y los métodos proporcionados por la clase Microsoft.VisualBasic.FileIO.FileSystem para la entrada y salida de archivos. |
Ejemplo
Imports System
Imports System.IO
Imports System.Text
Imports System.Collections.Generic
Class Program
Public Shared Sub Main(ByVal args As String())
Dim mydocpath As String = _
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Dim sb As New StringBuilder()
For Each txtName As String _
In Directory.EnumerateFiles(mydocpath, "*.txt")
Using sr As New StreamReader(txtName)
sb.AppendLine(txtName.ToString())
sb.AppendLine("= = = = = =")
sb.Append(sr.ReadToEnd())
sb.AppendLine()
sb.AppendLine()
End Using
Next
Using outfile As New StreamWriter(mydocpath & "\AllTxtFiles.txt")
outfile.Write(sb.ToString())
End Using
End Sub
End Class
using System;
using System.IO;
using System.Text;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
string mydocpath =
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StringBuilder sb = new StringBuilder();
foreach (string txtName in Directory.EnumerateFiles(mydocpath,"*.txt"))
{
using (StreamReader sr = new StreamReader(txtName))
{
sb.AppendLine(txtName.ToString());
sb.AppendLine("= = = = = =");
sb.Append(sr.ReadToEnd());
sb.AppendLine();
sb.AppendLine();
}
}
using (StreamWriter outfile =
new StreamWriter(mydocpath + @"\AllTxtFiles.txt"))
{
outfile.Write(sb.ToString());
}
}
}
using namespace System;
using namespace System::IO;
using namespace System::Text;
using namespace System::Collections::Generic;
ref class Program
{
public:
static void Main()
{
String^ mydocpath =
Environment::GetFolderPath(Environment::SpecialFolder::MyDocuments);
StringBuilder^ sb = gcnew StringBuilder();
for each (String^ txtName in Directory::EnumerateFiles(mydocpath, "*.txt"))
{
StreamReader^ sr = gcnew StreamReader(txtName);
sb->AppendLine(txtName->ToString());
sb->AppendLine("= = = = = =");
sb->Append(sr->ReadToEnd());
sb->AppendLine();
sb->AppendLine();
sr->Close();
}
StreamWriter^ outfile = gcnew StreamWriter(mydocpath + "\\AllTxtFiles.txt");
outfile->Write(sb->ToString());
outfile->Close();
}
};
int main()
{
Program::Main();
}
Vea también
Tareas
Cómo: Crear una lista de directorios
Cómo: Leer y escribir en un archivo de datos recién creado
Cómo: Abrir y anexar a un archivo de registro
Cómo: Leer texto de un archivo
Cómo: Leer caracteres de una cadena
Cómo: Escribir caracteres en una cadena