有效地读写文本文件

时间:2018-11-09 01:52:30

标签: c# file-io console

我有一个作业来创建C#控制台程序。它应该创建一个包含2个短语的文本文件:

世界,你好!
再见,残酷的世界!

然后,我还必须创建一个程序来读取文件中的2个短语。

两个小时后,这就是我所拥有的。它可以工作,但是我想重写该程序以提高效率。我主要在努力将文件输出到可以运行的.cs文件中。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace ConsoleApplication3
{    
    class Program
    {
        static void Main(string[] args)
        {
            //structure.txt contains the program we will enter our values into.
            String filePath = "Structure.txt";               
            WriteToFile(filePath);
        }

        public static void WriteToFile(string filePath)
        {
            //create a string array to gather our text file information.    
            StreamReader reader = new StreamReader(filePath);
            StreamReader info = new StreamReader("Structure.txt");

            StreamWriter writer = new StreamWriter("Hello.cs", true);
            String temp = String.Empty;

            while (!info.EndOfStream)
            {
                String tempstring = String.Empty;
                tempstring = reader.ReadLine();

                while (!reader.EndOfStream)
                {
                    temp = reader.ReadLine();
                    writer.WriteLine(temp);
                    if (temp == "//break")
                    {
                        writer.WriteLine("String1 = {}", tempstring);

                    }
                }
            }
            reader.Close();
            info.Close();

            writer.Close();
        }    
    }
}

1 个答案:

答案 0 :(得分:1)

效率更高?确定

// write
string[] lines = new [] {"Hello, World!", "Goodbye, Cruel World!"};
File.WriteAllLines("c:\\myFile.txt", lines);  

// read
string[] lines = File.ReadAllLines("c:\\myFile.txt");

这就是全部。 。 。