最简单的写文件

来源:互联网 发布:淘宝没发货退款 编辑:程序博客网 时间:2024/06/04 18:37

 

public static void Main() 

    {

        // Create an instance of StreamWriter to write text to a file.

        // The using statement also closes the StreamWriter.

        using (StreamWriter sw = new StreamWriter("TestFile.txt")) 

        {

            // Add some text to the file.

            sw.Write("This is the ");

            sw.WriteLine("header for the file.");

            sw.WriteLine("-------------------");

            // Arbitrary objects can also be written to the file.

            sw.Write("The date is: ");

            sw.WriteLine(DateTime.Now);

        }

    }

 

 

 

 

using System;

using System.IO;

public class TextToFile 

{

    private const string FILE_NAME = "MyFile.txt";

    public static void Main(String[] args) 

    {

        if (File.Exists(FILE_NAME)) 

        {

            Console.WriteLine("{0} already exists.", FILE_NAME);

            return;

        }

        using (StreamWriter sw = File.CreateText(FILE_NAME))

        {

            sw.WriteLine ("This is my file.");

            sw.WriteLine ("I can write ints {0} or floats {1}, and so on.", 

                1, 4.2);

            sw.Close();

        }

    }

}