sintassi:
File.metodo
metodi:
esempio:
string path = @"c:\temp\MyTest.txt";
FileStream fs = File.OpenRead(path)";
esempio:
using (StreamReader sr = File.OpenText(path))
{
string s = "";}
while ((s = sr.ReadLine()) != null)
{Console.WriteLine(s);}
esempio: crea file di testo ed insrisce testo
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))}
{sw.WriteLine("Buogniorno");}
sw.WriteLine("e");
sw.WriteLine("Buonanotte");
esempio: unione di due file di testo
string1 = @"c:\temp\MyTest1.txt";
string2 = @"c:\temp\MyTest2.txt";
string1.AppendText(stinga2);
esempio: aggiunta di testo
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("Questo");}
sw.WriteLine("e testo");
sw.WriteLine("extra");
esempio: unione di array di file
string filedestinazione = @"C:\Test\testunito.txt";
string[] fileunire = new string[] {"filetesto1.txt", "filetesto2.txt"};
foreach(string file in fileunire)
{
File.AppendAllText(filedestinazione, File.ReadAllText(file) + Environment.NewLine);}
per appendere un testo all'inizio non si usa AppendAllText ma si salva il file in una stringa di testo e poi si ricrea il file con il nuovo testo all'inizio:
string testocorrente = String.Empty;
if (File.Exists("path\file"))
{testocorrente = File.ReadAllText("path\file");}
File.WriteAllText("path\file", "testo_nuovo" + Environment.NewLine + testocorrente);