Csharp/CSharp Tutorial/File Directory Stream/Text File Read Write — различия между версиями
Admin (обсуждение | вклад) м (1 версия) |
|
(нет различий)
|
Версия 15:31, 26 мая 2010
Содержание
- 1 Create a file called test.txt in the current directory:
- 2 Display a text file.
- 3 Get interal StringBuilder from a StringWriter
- 4 Reading Writing To Text File
- 5 Read text file line by line
- 6 Read/Write text file using the StringWriter
- 7 Simple IO with the File Type
- 8 Use while loop to read a text file
- 9 Write and read text file using StreamWriter
- 10 Write text file line by line
- 11 Write to a file
Create a file called test.txt in the current directory:
using System;
using System.IO;
class Program {
static void Main() {
using (Stream s = new FileStream("test.txt", FileMode.Create)) {
Console.WriteLine(s.CanRead); // true
Console.WriteLine(s.CanWrite); // true
Console.WriteLine(s.CanSeek); // true
s.WriteByte(101);
s.WriteByte(102);
byte[] block = { 1, 2, 3, 4, 5 };
s.Write(block, 0, block.Length); // Write block of 5 bytes
Console.WriteLine(s.Length); // 7
Console.WriteLine(s.Position); // 7
s.Position = 0; // Move back to the start
Console.WriteLine(s.ReadByte()); // 101
Console.WriteLine(s.ReadByte()); // 102
Console.WriteLine(s.Read(block, 0, block.Length)); // 5
Console.WriteLine(s.Read(block, 0, block.Length)); // 0
}
}
}
Display a text file.
using System;
using System.IO;
class MainClass {
public static void Main(string[] args) {
int i;
FileStream fin;
try {
fin = new FileStream("test.txt", FileMode.Open);
} catch(FileNotFoundException exc) {
Console.WriteLine(exc.Message);
return;
} catch(IndexOutOfRangeException exc) {
Console.WriteLine(exc.Message + "\nUsage: ShowFile File");
return;
}
// read bytes until EOF is encountered
do {
try {
i = fin.ReadByte();
} catch(Exception exc) {
Console.WriteLine(exc.Message);
return;
}
if(i != -1) Console.Write((char) i);
} while(i != -1);
fin.Close();
}
}
Get interal StringBuilder from a StringWriter
using System;
using System.IO;
using System.Text;
public class MainClass
{
public static int Main(string[] args)
{
// Get a StringWriter and write some stuff.
StringWriter writer = new StringWriter();
writer.WriteLine("string 1");
for(int i = 0; i < 10; i++)
{
writer.Write(i + " ");
}
writer.Write(writer.NewLine);
writer.Close();
Console.WriteLine("Contents:\n{0}", writer);
StringBuilder str = writer.GetStringBuilder();
string allOfTheData = str.ToString();
Console.WriteLine("-> StringBuilder says:\n{0}", allOfTheData);
str.Insert(20, "INSERTED STUFF");
allOfTheData = str.ToString();
Console.WriteLine("-> New StringBuilder says:\n{0}", allOfTheData);
StringReader sr = new StringReader(writer.ToString());
string input = null;
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine (input);
}
sr.Close();
return 0;
}
}
Contents: string 1 0 1 2 3 4 5 6 7 8 9 -> StringBuilder says: string 1 0 1 2 3 4 5 6 7 8 9 -> New StringBuilder says: string 1 0 1 2 3 4 INSERTED STUFF5 6 7 8 9 string 1 0 1 2 3 4 INSERTED STUFF5 6 7 8 9
Reading Writing To Text File
using System;
using System.IO;
class Tester
{
public static void Main()
{
FileInfo theSourceFile = new FileInfo("test.cs");
StreamReader reader = theSourceFile.OpenText();
StreamWriter writer = new StreamWriter("test.bak", false);
string text;
do
{
text = reader.ReadLine();
writer.WriteLine(text);
Console.WriteLine(text);
} while (text != null);
reader.Close();
writer.Close();
}
}
Read text file line by line
using System;
using System.IO;
class MainClass
{
public static void Main()
{
FileStream outStream = File.Create("c:\\Test.txt");
StreamWriter sw = new StreamWriter(outStream);
sw.WriteLine("This is a test of the StreamWriter class");
sw.Flush();
sw.Close();
StreamReader sr = new StreamReader("c:\\Test.txt");
string FirstLine;
FirstLine = sr.ReadLine();
Console.WriteLine(FirstLine);
sr.Close();
}
}
Read/Write text file using the StringWriter
using System;
using System.IO;
using System.Text;
public class MainClass
{
public static int Main(string[] args)
{
// Get a StringWriter and write some stuff.
StringWriter writer = new StringWriter();
writer.WriteLine("string 1");
for(int i = 0; i < 10; i++)
{
writer.Write(i + " ");
}
writer.Write(writer.NewLine);
writer.Close();
Console.WriteLine("Contents:\n{0}", writer);
StringBuilder str = writer.GetStringBuilder();
string allOfTheData = str.ToString();
Console.WriteLine("-> StringBuilder says:\n{0}", allOfTheData);
str.Insert(20, "INSERTED STUFF");
allOfTheData = str.ToString();
Console.WriteLine("-> New StringBuilder says:\n{0}", allOfTheData);
StringReader sr = new StringReader(writer.ToString());
string input = null;
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine (input);
}
sr.Close();
return 0;
}
}
Contents: string 1 0 1 2 3 4 5 6 7 8 9 -> StringBuilder says: string 1 0 1 2 3 4 5 6 7 8 9 -> New StringBuilder says: string 1 0 1 2 3 4 INSERTED STUFF5 6 7 8 9 string 1 0 1 2 3 4 INSERTED STUFF5 6 7 8 9
Simple IO with the File Type
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string[] myTasks = {"A", "C","C", "P"};
File.WriteAllLines(@"C:\tasks.txt", myTasks);
foreach (string task in File.ReadAllLines(@"C:\tasks.txt"))
{
Console.WriteLine("TODO: {0}", task);
}
}
}
Use while loop to read a text file
using System;
using System.IO;
class MainClass
{
public static void Main(string[] args)
{
try
{
StreamReader sr = File.OpenText("c:\\boot.ini");
string strLine;
while(null != (strLine = sr.ReadLine()))
{
Console.WriteLine(strLine);
}
sr.Close();
}
catch(FileNotFoundException e)
{
Console.WriteLine(e.Message);
}
}
}
[boot loader] timeout=30 default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS [operating systems] multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Home Edition" /noexecute=optin /fa stdetect
Write and read text file using StreamWriter
using System;
using System.IO;
public class MainClass
{
public static int Main(string[] args)
{
FileInfo f = new FileInfo("test.txt");
StreamWriter writer = f.CreateText();
writer.WriteLine("string 1");
writer.WriteLine("string 2");
for(int i = 0; i < 10; i++)
{
writer.Write(i + " ");
}
writer.Write(writer.NewLine);
writer.Close();
// Now read it all back in.
StreamReader sr = File.OpenText("test.txt");
string input = null;
while ((input = sr.ReadLine()) != null)
{
Console.WriteLine (input);
}
return 0;
}
}
string 1 string 2 0 1 2 3 4 5 6 7 8 9
Write text file line by line
using System;
using System.IO;
class MainClass
{
public static void Main()
{
FileStream outStream = File.Create("c:\\Test.txt");
StreamWriter sw = new StreamWriter(outStream);
sw.WriteLine("This is a test of the StreamWriter class");
sw.Flush();
sw.Close();
StreamReader sr = new StreamReader("c:\\Test.txt");
string FirstLine;
FirstLine = sr.ReadLine();
Console.WriteLine(FirstLine);
sr.Close();
}
}
Write to a file
using System;
using System.IO;
class MainClass {
public static void Main(string[] args) {
FileStream fout;
// open output file
try {
fout = new FileStream("test.txt", FileMode.Create);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "\nError Opening Output File");
return;
}
// Write the alphabet to the file.
try {
for(char c = "A"; c <= "Z"; c++)
fout.WriteByte((byte) c);
} catch(IOException exc) {
Console.WriteLine(exc.Message + "File Error");
}
fout.Close();
}
}