www.xbdev.net
xbdev - software development
Thursday March 28, 2024
home | contact | Support | Programming.. With C# and .Net...

     
 

Programming..

With C# and .Net...

 

Writing to a file with C#

 

As with everything, we must start somewhere, and that somewhere is here at main()...

 

Code:

// files.cs

 

class abc

{

      static void Main()

      {

            /* our program entry point*/

      }

}

 

 

 

Code:

// files.cs

 

// You will usually need

using System.IO;

// for input output operations

 

class abc

{

      static void Main()

      {

            // FileMode - Append, Create, CreateNew, Open, OpenOrCreate, or Truncate

            // FileAccess - Read, ReadWrite, or Write

 

            FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);

      }

}

 

But of course, this is bad, we are opening a file, or should I say creating a file, but not closing our file handle.... which we'll do in the next part :)

 

Code:

// files.cs

 

// You will usually need

using System.IO;

// for input output operations

 

class abc

{

      static void Main()

      {

            // FileMode - Append, Create, CreateNew, Open, OpenOrCreate, or Truncate

            // FileAccess - Read, ReadWrite, or Write

 

            FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Write);

 

            // Create a new stream to write to the file

            StreamWriter sw = new StreamWriter(file);

 

            // Write a string to the file

            sw.Write("Hello file system world!");

 

            // Close StreamWriter

            sw.Close();

 

            // Close file

            file.Close();

      }

}

 

 

 

Code:

// files.cs

 

// You will usually need

using System.IO;

// for input output operations

 

class abc

{

      static void Main()

      {

            // FileMode - Append, Create, CreateNew, Open, OpenOrCreate, or Truncate

            // FileAccess - Read, ReadWrite, or Write

 

            // Read the whole file contents in

            FileStream file = new FileStream("test.txt", FileMode.OpenOrCreate, FileAccess.Read);

 

            // Create a new stream to read from a file

            StreamReader sr = new StreamReader(file);

 

            // Read contents of file into a string

            string s = sr.ReadToEnd();

 

            // Close StreamReader

            sr.Close();

 

            // Close file

            file.Close();

      }

}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
Advert (Support Website)

 
 Visitor:
Copyright (c) 2002-2024 xbdev.net - All rights reserved.
Designated articles, tutorials and software are the property of their respective owners.