如何将文件名/路径传递给文本解析器

本文关键字:文本 文件名 路径 | 更新日期: 2023-09-27 18:14:07

我试图在VS2015中获得一个简单的文本解析器类。我收到了类代码并构建了一个基本的控制台应用程序,添加了Cawk类并尝试编译/运行它。

我得到的主要错误是

参数1:不能从'string'转换为'System.IO.StreamReader'

很明显,我不知道如何通过Main传递文件名到Cawk。我如何给它一个文件名的参数?

任何帮助或指示将不胜感激。

我Program.cs

:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication3
{
    class Program
        {
        static void Main()
        {
            string input = @"c:'temp'test.txt";
            Cawk.Execute(input);
        }
    }
}

My caw .cs代码片段:

using System;
using System.Collections.Generic;
using System.IO;
namespace ConsoleApplication3
{
    public static class Cawk
    {
        public static IEnumerable<Dictionary<string, object>> Execute(StreamReader input)
    {
        Dictionary<string, object> row = new Dictionary<string, object>();
        string line;
        //string[] lines = File.ReadAllLines(path);
        //read all rows
        while ((line = input.ReadLine()) != null)
        {

如何将文件名/路径传递给文本解析器

Execute接受一个StreamReader而不是字符串。

Cawk.Execute(new StreamReader(@"c:'temp'test.txt"))

但是,您应该在完成流之后关闭它。

using (var sr = new StreamReader(@"c:'temp'test.txt"))
{
    Cawk.Execute(sr);
}

类似于

var sr = new System.IO.StreamReader(@"c:'temp'test.txt");
Cawk.Execute(sr);

直接使用System.IO命名空间中的File

Cawk.Execute(File.OpenText(@"c:'temp'test.txt"));

像这样:

string input = @"c:'temp'test.txt";
Cawk.Execute(new System.IO.StreamReader(input));

你可以把using System.IO;像其他用法一样放到最上面,这样以后就不必把它写出来了。