【问题标题】:How to save a streamed document and use information on document in C#如何在 C# 中保存流式文档并使用文档上的信息
【发布时间】:2012-11-20 16:56:48
【问题描述】:

您好,我目前正在完成编程课的最后一项作业,而且我对编程领域还很陌生。我的任务是通过 Streamreader 流式传输文档并提取信息以供菜单程序访问文档。

到目前为止,我只能流式传输

using System;
using System.IO;

class Test
{
    public static void Main()
    {
        try
        {
            Directory.SetCurrentDirectory(@"\Users\changl\Desktop");

            using (StreamReader sr = new StreamReader("earthquakes.csv"))
            {
                String line;

                while ((line = sr.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
            }
        }
        catch (Exception e)
        {

            Console.WriteLine("The file could not be read:");
            Console.WriteLine(e.Message);
        }
    }
}

我在编程方面颇有经验,希望得到一些帮助,了解下一步如何将信息保存在文档中以供以后使用。

【问题讨论】:

    标签: c# parsing csv


    【解决方案1】:

    Console.Writeline 只是将信息写入控制台窗口,您需要某种形式的方法来保存它..

    using (StreamReader sr = new StreamReader("earthquakes.csv"))
        {
            String line;
            List<string> myList = new List<string>();
    
            while ((line = sr.ReadLine()) != null)
            {
               // Console.WriteLine(line);
                myList.add(line);
            }
        }
    

    【讨论】:

    • 收到错误提示“未找到列表的类型或名称空间。
    • 使用 System.Collections.Generic;
    【解决方案2】:

    你只需用,,;,\t分割每一行:

    var fieldsEnumerable = sr.ReadLine().Split(',');
    

    但是this library 会为你做这件事:

    List<List<string>> records = new List<List<string>>();
    
    using (CsvReader reader = new CsvReader(FilePath, Encoding.Default))
    {
        while (reader.ReadNextRecord())
            records.Add(reader.Fields);
    } 
    

    【讨论】:

    • 我以前尝试过类似的方法,但我收到一条错误消息,提示“未找到列表的类型或名称空间。”
    • 第一个示例已更新,请尝试。首先查看您的文件并确保 , (comma) 已分隔每个字段。
    • 对不起,我对这个网站完全陌生,我不知道如何在这里发布整个代码....我要编辑原始帖子吗?
    • 是的,编辑原始帖子,并添加您的代码和 StackTrace:stackoverflow.com/questions/945193/…
    猜你喜欢
    • 2013-10-08
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 1970-01-01
    • 2018-05-10
    • 1970-01-01
    • 2015-12-01
    相关资源
    最近更新 更多