无法在Visual Studio

时间:2017-05-01 19:20:58

标签: c# readfile streamreader

我正在尝试编写一段代码,其中一件事就是逐行读取.txt文件。但是,我不断获得“对象引用是必需的”#39;错误。我不知道如何阅读文件会导致如此多的问题,但它有。这是我的代码(在开始之前忽略注释掉的位):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
//(Program)
namespace FileReader
{
class ReadFromFile
{
    public void IsValidLine(string text)
    {
        Regex rgx = new Regex(@"^([A-Za-z]{1,5})((\s\d){0,9})(\s*)$");
        if (rgx.IsMatch(text) == false)
        {
            Console.WriteLine("Invalid Format");
        }

    }
    static void Main()
    {
        System.IO.StreamReader file = new 
System.IO.StreamReader(@"C:\Users\Public\TestFolder\WriteLines2.txt");
        {
            int counter = 0;
            string line;
            List<string> lines = new List<string>();


            while ((line = file.ReadLine()) != null)
            {
                //HERE IS THE ERROR
                IsValidLine(line); 
                lines.Add(line);
                counter++;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

问题是您在静态上下文中访问非静态类 - 因此您需要引用该类的对象。所以你要做的就是让方法成为静态的:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text.RegularExpressions;
//(Program)
namespace FileReader
{
class ReadFromFile
{
    public static void IsValidLine(string text)
    {
        Regex rgx = new Regex(@"^([A-Za-z]{1,5})((\s\d){0,9})(\s*)$");
        if (rgx.IsMatch(text) == false)
        {
            Console.WriteLine("Invalid Format");
        }

    }
    static void Main()
    {
        System.IO.StreamReader file = new 
System.IO.StreamReader(@"C:\Users\Public\TestFolder\WriteLines2.txt");
        {
            int counter = 0;
            string line;
            List<string> lines = new List<string>();


            while ((line = file.ReadLine()) != null)
            {
                //HERE IS THE ERROR
                IsValidLine(line); 
                lines.Add(line);
                counter++;
            }
        }
    }
}

为避免此类错误,我建议将该类设为静态:

static class ReadFromFile
//...

如果类中没有任何静态代码,则代码不会编译。