String Array to text document and read it

时间:2014-09-15 03:53:41

标签: c# arrays console

我在编写程序时遇到问题。 我需要做它,以便它检查是否存在文本文件,如果它存在则显示内容,如果不存在则提示用户输入5个名称,这些名称存储到数组中然后发送到文本文档。我已经尝试过这样做但是我收到了一个错误。

注意: 我需要在数组中做名字。

代码:

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

namespace Array
{
    class Program
    {
        public static string line;
        public const string file = @"D:\information.txt";
        public static string names = @"D:\names.txt";
        public static StreamReader myFile = new StreamReader(names);
        public static string[] namesArray = new string[4];

        public static bool checkFileExists(string names)    
        {
            bool b = false;
            if (File.Exists(names))
            {
                b = true;
            }
            return b;
        }

        static void reset() //void used to reset the program
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.Write("\nIf there is an error, press Enter to restart");
            Console.ForegroundColor = ConsoleColor.White; //changes the text colour of the next line of code to white, better visuals
            Console.ReadLine(); //the readkey used to read for any keys being pressed for restarting
            Console.Clear(); //clears the console and resets it back to normal
        }

        static void toFile()
        {
            Console.ForegroundColor = ConsoleColor.White;
            string[] namesArray = new string[5];
            Random RandString = new Random();

            StreamWriter info = new StreamWriter(file);

            for (int x = 0; x < namesArray.Length; x++)
            {
                Console.Write("Enter a name of class member: {0}", namesArray[x]);
                namesArray[x] = Console.ReadLine();
            }

            for (int x = 0; x < namesArray.Length; x++)
            {
                info.WriteLine("{0}", namesArray[x]);
            }
            info.Close();
        }

        static void Main(string[] args)
        {
            Console.Title = "Class names to array";
                try
                {
                    if (checkFileExists(names))
                    {
                        Console.WriteLine("file exists, the contents of the file is: ");
                        while (myFile1.EndOfStream == false)
                        {
                            line = myFile1.ReadLine();
                            Console.WriteLine(line);
                        }
                        Console.ReadLine();
                    }
                    else
                    {
                        toFile();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: " + e.Message);
                }
        }
    }

我得到的错误是''Array.Program'的类型初始化程序引发异常'并且它只是关闭。

我的一位朋友也告诉我,我的代码非常混乱,我不确定我需要做些什么才能让它变得更好但是感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

检查调试器中“内部异常”的详细信息。您应该看到问题出在这一行:

public static StreamReader myFile = new StreamReader(names);

这是唯一可能导致此问题的行,可能是因为names字段包含的文件名不存在,或者您无法访问它(权限或共享冲突,例如)。纠正内部异常指示的问题,以使异常停止发生。

请注意,如果您在Main()方法中执行此分配,则TypeInitializationException不会屏蔽实际错误,只要静态构造函数抛出异常就会抛出该错误。

答案 1 :(得分:0)

正如@cdhowie所说,你会在InnerException中找到细节。我确实注意到你的代码有点紧张,而且确实很混乱,所以我决定写一个小样本来做你想要的东西,减少行数。很多时候,在进行简单的文件操作时,您可以避免使用StreamReaderStreamWriter,而只需使用File class

以下是代码示例:

using System;
using System.IO;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string file = @"D:\information.txt";
            if (File.Exists(file))
                foreach(var s in File.ReadAllLines(file))
                    Console.WriteLine(s);
            else
            {
                string[] src = new string[5];
                Console.WriteLine("Please enter 5 names:");
                for (int i = 0; i < 5; i++)
                    src[i] = Console.ReadLine();
                File.Create(file).Close();
                File.WriteAllLines(file, src)
            }
        }
    }
}