Csharp/CSharp Tutorial/File Directory Stream/StreamWriter

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

Create StringWriter from StringBuilder

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();
  }
}
This is a test of the StringWriter class

new StreamWriter(fs, Encoding.UTF8)

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()));
            }
        }
    }
}

Open a file using StreamWriter

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(); 
  } 
}

Reading and Writing Files

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();
    }
}

Save string, decimal and char using FileStream and StreamWriter

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()));
            }
        }
    }
}
124.23
Test string
A

StreamWriter/Reader App

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);
        }
      }
    }
  }

Stream Write with StreamWriter

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();
        }
    }

StringReader/Writer App

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);
          }
        }
      }
    }
  }

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

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();
    }
}

Using statement and StreamWriter

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?");
      }
    }
}

Using StreamWriter: write a portion of an array

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();
  }
}

Using StreamWriter: write char

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();
  }
}

Using StreamWriter: Writes an Array of characters

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();
  }
}

Using StreamWriter: write string

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();
  }
}