C# 高效地读写文本文件

C# 高效地读写文本文件,c#,file-io,console,C#,File Io,Console,我有一个家庭作业,要创建一个C#控制台程序。它应该创建一个包含两个短语的文本文件: 你好,世界 再见,残酷的世界 然后我还必须创建一个程序来读取文件中的两个短语 两个小时后,这就是我所拥有的。它可以工作,但我想重写程序以提高效率。我主要研究如何将文件输出到能够运行的.cs文件中 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.T

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

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

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

两个小时后,这就是我所拥有的。它可以工作,但我想重写程序以提高效率。我主要研究如何将文件输出到能够运行的.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();
        }    
    }
}
更有效率?当然

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

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

这都是

如果你使用and,你可以用更少的代码来解决这个问题。请你的标题反映你的问题,而不是你问的原因。请参阅,特别是关于编写一个好标题的部分。另外,如果您使用流,您应该处理它们,或者更好地使用
using
station。我投票将这个问题作为离题题来结束,因为它要求改进工作代码,而不是编程问题。它可能更适合作为替代品。