uccjshrimpton

C# Writing to a File

Nov 15th, 2016
742
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.27 KB | None | 0 0
  1.             // Example #1: Write an array of strings to a file.
  2.             // Create a string array that consists of three lines.
  3.             string[] lines = { "First line", "Second line", "Third line" };
  4.             // WriteAllLines creates a file, writes a collection of strings to the file,
  5.             // and then closes the file.  You do NOT need to call Flush() or Close().
  6.             System.IO.File.WriteAllLines(@"S:\Visual Studio 2015\Projects\WriteLines.txt", lines);
  7.  
  8.  
  9.             // Example #2: Write one string to a text file.
  10.             string text = "A class is the most powerful data type in C#. Like a structure, " +
  11.                            "a class defines the data and behavior of the data type. ";
  12.             // WriteAllText creates a file, writes the specified string to the file,
  13.             // and then closes the file.    You do NOT need to call Flush() or Close().
  14.             System.IO.File.WriteAllText(@"S:\Visual Studio 2015\Projects\WriteText.txt", text);
  15.  
  16.             // Example #3: Write only some strings in an array to a file.
  17.             // The using statement automatically flushes AND CLOSES the stream and calls
  18.             // IDisposable.Dispose on the stream object.
  19.             // NOTE: do not use FileStream for text files because it writes bytes, but StreamWriter
  20.             // encodes the output as text.
  21.             using (System.IO.StreamWriter file =
  22.                 new System.IO.StreamWriter(@"S:\Visual Studio 2015\Projects\WriteLines2.txt"))
  23.             {
  24.                 foreach (string line in lines)
  25.                 {
  26.                     // If the line doesn't contain the word 'Second', write the line to the file.
  27.                     if (!line.Contains("Second"))
  28.                     {
  29.                         file.WriteLine(line);
  30.                     }
  31.                 }
  32.             }
  33.  
  34.             // Example #4: Append new text to an existing file.
  35.             // The using statement automatically flushes AND CLOSES the stream and calls
  36.             // IDisposable.Dispose on the stream object.
  37.             using (System.IO.StreamWriter file =
  38.                 new System.IO.StreamWriter(@"S:\Visual Studio 2015\Projects\WriteLines2.txt", true))
  39.             {
  40.                 file.WriteLine("Fourth line");
  41.             }
Advertisement
Add Comment
Please, Sign In to add comment