C#程序读取,写入控制台,但不写入文件

时间:2016-05-05 14:42:05

标签: c# streamwriter

我正在尝试使用C#按字母顺序排列文本文件中的所有单词。我能够读取文件并正确填写列表。然后我可以遍历列表并打印到控制台。但是,当我在迭代时,我也在尝试写入输出文件。当控制台正确打印所有单词时,我似乎无法确定输出文件为空的原因。文件sortedProposal.txt已创建,但为空。

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

namespace IO_Practice
{
    class Program
    {
        static void Main(string[] args)
        {
            //get the directory of the text file
            string directory = Directory.GetCurrentDirectory();
            string cd = (Path.Combine(directory, @"..\..\"));
            string infileHandle = cd + "AModestProposal.txt";


            //print to screen for testing 
            Console.WriteLine(infileHandle);

            //Holds all the words in the story
            List<string> words = new List<string>();

            //Holds the words from one line
            string[] wordHolder;

            //Holds each line as it's read
            string line;

            using (StreamReader sr = new StreamReader(infileHandle))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    //print to console
                    Console.WriteLine(line);

                    //split line into array
                    wordHolder = line.Split(' ');

                    //add array to vector
                    words.AddRange(wordHolder);
                }
            }

            words.Sort();

            //Debug
            Console.WriteLine("Length of List: " + words.Count());

            //create the outfile
            string outfileHandle = cd + "sortedProposal.txt";

            using(StreamWriter sw = new StreamWriter(outfileHandle)) {
                foreach(string word in words)
                {
                     sw.WriteLine(word);
                     //Debug
                    Console.WriteLine(word);

                }
            }
        }
    }
}

0 个答案:

没有答案