Csharp/CSharp Tutorial/File Directory Stream/StreamWriter — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Версия 18:31, 26 мая 2010

Create StringWriter from StringBuilder

<source lang="csharp">using System; using System.IO; using System.Text; class MainClass {

 public static void Main() 
 {
   StringBuilder sb = new StringBuilder();
   StringWriter sw = new StringWriter(sb);
   sw.Write("This is a test of the StringWriter class");
   sw.Close();
   StringReader sr = new StringReader(sb.ToString());
   string EntireString;
 
   EntireString = sr.ReadToEnd();
   Console.WriteLine(EntireString);
   sr.Close();
 }

}</source>

This is a test of the StringWriter class

new StreamWriter(fs, Encoding.UTF8)

<source lang="csharp">using System; using System.IO; using System.Text; class MainClass {

   static void Main() {
       using (FileStream fs = new FileStream("test.txt", FileMode.Create)) {
           using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8)) {
               w.WriteLine(124.23M);
               w.WriteLine("Test string");
               w.WriteLine("!");
           }
       }
       Console.WriteLine("Press Enter to read the information.");
       Console.ReadLine();
       using (FileStream fs = new FileStream("test.txt", FileMode.Open)) {
           using (StreamReader r = new StreamReader(fs, Encoding.UTF8)) {
               Console.WriteLine(Decimal.Parse(r.ReadLine()));
               Console.WriteLine(r.ReadLine());
               Console.WriteLine(Char.Parse(r.ReadLine()));
           }
       }
   }

}</source>

Open a file using StreamWriter

<source lang="csharp">using System; using System.IO;

class MainClass {

 public static void Main() { 

   StreamWriter fstr_out; 

   try { 
     fstr_out = new StreamWriter("test.txt"); 
   } 
   catch(IOException exc) { 
     Console.WriteLine(exc.Message + "Cannot open file."); 
     return ; 
   } 

   try { 
      fstr_out.Write("asdfasdf"); 
   } catch(IOException exc) { 
      Console.WriteLine(exc.Message + "File Error"); 
      return ; 
   } 

   fstr_out.Close(); 
 } 

}</source>

Reading and Writing Files

<source lang="csharp">using System; using System.IO; class MainClass {

   public static void Main()
   {
       FileStream f = new FileStream("output.txt", FileMode.Create);
       StreamWriter s = new StreamWriter(f);
       
       s.WriteLine("{0} {1}", "test", 55);
       s.Close();
       f.Close();
   }

}</source>

Save string, decimal and char using FileStream and StreamWriter

<source lang="csharp">using System; using System.IO; using System.Text; static class MainClass {

   static void Main()
   {
       // Create a new file.
       using (FileStream fs = new FileStream("test.txt", FileMode.Create))
       {
           using (StreamWriter w = new StreamWriter(fs, Encoding.UTF8))
           {
               // Write a decimal, string, and char.
               w.WriteLine(124.23M);
               w.WriteLine("Test string");
               w.WriteLine("A");
           }
       }
       // Open the file in read-only mode.
       using (FileStream fs = new FileStream("test.txt", FileMode.Open))
       {
           using (StreamReader r = new StreamReader(fs, Encoding.UTF8))
           {
               // Read the data and convert it to the appropriate data type.
               Console.WriteLine(Decimal.Parse(r.ReadLine()));
               Console.WriteLine(r.ReadLine());
               Console.WriteLine(Char.Parse(r.ReadLine()));
           }
       }
   }

}</source>

124.23
Test string
A

StreamWriter/Reader App

<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.IO;

 class Program
 {
   static void Main(string[] args)
   {
     using (StreamWriter writer = new StreamWriter("reminders.txt"))
     {
       writer.WriteLine("A");
       writer.WriteLine("B");
       writer.WriteLine("C");
       for (int i = 0; i < 10; i++)
         writer.Write(i + " ");
       writer.Write(writer.NewLine);
     }
     using (StreamReader sr = new StreamReader("reminders.txt"))
     {
       string input = null;
       while ((input = sr.ReadLine()) != null)
       {
         Console.WriteLine(input);
       }
     }
   }
 }</source>

Stream Write with StreamWriter

<source lang="csharp">using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;

   class Program
   {
       static void Main(string[] args)
       {
               FileStream aFile = new FileStream("Log.txt", FileMode.OpenOrCreate);
               StreamWriter sw = new StreamWriter(aFile);
               bool truth = true;
               sw.WriteLine("Hello to you.");
               sw.WriteLine("It is now {0} and things are looking good.",DateTime.Now.ToLongDateString());
               sw.Write("More than that,");
               sw.Write(" it"s {0} that C# is fun.", truth);
               sw.Close();
       }
   }</source>

StringReader/Writer App

<source lang="csharp">using System; using System.Collections.Generic; using System.Text; using System.IO;

 class Program
 {
   static void Main(string[] args)
   {
     using (StringWriter strWriter = new StringWriter())
     {
       strWriter.WriteLine("A");
       Console.WriteLine(strWriter);
       StringBuilder sb = strWriter.GetStringBuilder();
       sb.Insert(0, "Hey!! ");
       Console.WriteLine("-> {0}", sb.ToString());
       sb.Remove(0, "Hey!! ".Length);
       Console.WriteLine("-> {0}", sb.ToString());
       using (StringReader strReader = new StringReader(strWriter.ToString()))
       {
         string input = null;
         while ((input = strReader.ReadLine()) != null)
         {
           Console.WriteLine(input);
         }
       }
     }
   }
 }</source>

Using File.CreateText to create a text file and return StreamWriter

<source lang="csharp">using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Windows.Forms; using System.IO;

class MainClass {

   public static void Main()
   {
       StreamWriter Writer;
       Writer = File.CreateText("TestResults.log");
       Writer.WriteLine("Test Results for Test Run XYZ; " + DateTime.Now);
       if (File.Exists("fileName"))
       {
           Writer.WriteLine("File Exists: Test Passed");
       }
       else
       {
           Writer.WriteLine("File Exists: Test Failed");
       }
       Writer.WriteLine("Test Completed for Test Run XYZ; " + DateTime.Now);
       Writer.Close();
   }

}</source>

Using statement and StreamWriter

<source lang="csharp">using System; using System.Collections.Generic; using System.ruponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using System.IO.IsolatedStorage; using System.Security.Permissions; [assembly: IsolatedStorageFilePermission(SecurityAction.RequestMinimum, UsageAllowed = IsolatedStorageContainment.AssemblyIsolationByUser)] public class MainClass{

   public static void Main()
   {
     using (StreamWriter sw = new StreamWriter(@"C:\MyData.txt"))
     {
       sw.WriteLine("This is my data.");
       sw.WriteLine("Cool, huh?");
     }
   }

}</source>

Using StreamWriter: write a portion of an array

<source lang="csharp">using System; using System.IO; public class MainClass {

 static void Main(string[] args)
 {
   StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt");
   char[] MyCharArray = new char[100];
   for (int i = 0; i < 99; i++)
   {
     MyCharArray[i] = (char)i;
   }
   MyStreamWriter.Write(MyCharArray, 25, 30);
   MyStreamWriter.Close();
 }

}</source>

Using StreamWriter: write char

<source lang="csharp">using System; using System.IO; public class MainClass {

 static void Main(string[] args)
 {
   StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt");
   //Writes single characters to a stream
   char MyChar = "A";
   MyStreamWriter.Write(MyChar);
   MyStreamWriter.Close();
 }

}</source>

Using StreamWriter: Writes an Array of characters

<source lang="csharp">using System; using System.IO; public class MainClass {

 static void Main(string[] args)
 {
   StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt");
   char[] MyCharArray = new char[100];
   for (int i = 0; i < 99; i++)
   {
     MyCharArray[i] = (char)i;
   }
   MyStreamWriter.Write(MyCharArray);
   MyStreamWriter.Close();
 }

}</source>

Using StreamWriter: write string

<source lang="csharp">using System; using System.IO; public class MainClass {

 static void Main(string[] args)
 {
   StreamWriter MyStreamWriter = new StreamWriter(@"c:\Testing.txt");
   
   string MyString = "Hello World";
   MyStreamWriter.Write(MyString);
   MyStreamWriter.Close();
 }

}</source>