【问题标题】:unable to read text file using stream reader and place txt into custom class无法使用流阅读器读取文本文件并将 txt 放入自定义类
【发布时间】:2018-08-02 04:21:12
【问题描述】:

所以我试图从 txt 文件中读取文本,然后将文本添加到自定义类列表中,

代码是

public static List<BookInfo> LoadCSVFile(string fileName, out string qError)
    {
        qError = "";
        fileName = "books.txt";
        List<BookInfo> Book_Info = new List<BookInfo>();
        StreamReader read = null;

        try
        {
            read = new StreamReader(fileName);
            while (!read.EndOfStream)
            {
                string line = read.ReadLine();
                string[] values = line.Split(',');
                if (values.Length == 3)
                {
                    string Title = values[0].Trim();
                    string Author = values[1].Trim();
                    string ISBN = values[2].Trim();

                    try
                    {
                        Book_Info.Add(new BookInfo(Title, Author, ISBN));
                    }
                    catch (Exception ex)
                    {
                        qError = ex.Message;
                        return null;
                    }
                }
                else
                {
                    qError = $"line {line} was unable to be read";
                    return null;
                }
            }
        }
        catch
        {
            qError = $"failed to open file: {fileName}";
            return null;
        }
        finally
        {
            if (read != null)
            {
                read.Close();
            }
        }
        if (qError == "")
        {
            return Book_Info;
        }
        return null;
    }

一旦我阅读了文本,它将以我认为正确编码的形式显示

我已经放置了一条错误消息以显示文件何时被读取,并且每次我尝试新的东西时都会出现相同的错误。

我在读取 txt 文件的时候是不是哪里出错了?

编辑:

文本文件是使用 Visual Studio 创建的,并且在同一个解决方案中,文本文件在 bin/debug 中

【问题讨论】:

  • 您的文件在哪里?如果 bin 文件夹中不存在文件,则必须在 StreamReader() 中传递文件路径
  • 我在 Visual Studio 中创建了 txt 文件,并且在同一个解决方案中
  • StreamReader()之前,检查if(File.Exists(fileName));我猜您还没有将文本文件的属性更改为 始终复制

标签: c# forms winforms class streamreader


【解决方案1】:

我完全同意将军的回答,但要回答您最初的问题,我怀疑您的 books.txt 文件不在您的 Bin/Debug 文件夹中。 I did test your code ;-P

【讨论】:

    【解决方案2】:

    一些笔记

    1. 如果您要使用实现IDisposable 的东西,使用using 语句总是好的做法

    2. 如果这只是一个小文件,既然可以使用File.ReadAllLines,为什么还要麻烦StreamReader

    3. Linq 是你的朋友,投影是个好东西。

    4. 如果您真的想解析 CSV,请认真考虑使用专用的 CSV 解析器库(如 CsvHelper),它将为您省去很多麻烦,很多很多

    这并不是完美编码的真正堡垒,但是我尝试使用您所拥有的以及您正在尝试做的事情的精神。

    一些 Codez

    public static List<BookInfo> LoadCSVFile(string fileName, out string qError)
    {
       try
       {
    
          // read all lines in to another type
          // just makes it easier for errors which you seem to want
          var lines = File.ReadAllLines(fileName)
                          .Select(x => new { Values = x.Split(','), Text = x })
                          .ToList();
    
          // get a list of errors, 
          var errors = lines.Where(x => x.Values.Length != 3)
                            .Select((s, i) => $"Bad book! Line {i} : {s.Text}");
    
          // return some errors
          qError = string.Join(Environment.NewLine, errors);
    
          // project lines to your books    
          return lines.Where(x => x.Values.Length == 3)
                      .Select(x => new BookInfo(x.Values[0], x.Values[0], x.Values[0]))
                      .ToList();
       }
       catch (Exception e)
       {
          qError = e.Message;
       }
    
       return null;
    }
    

    免责声明

    • 我通常不会发现这样的错误,它相当讨厌
    • 整个匿名类型和返回错误有点臭,如果文件损坏,id 只是抛出一个严重的异常并处理它。让用户做正确的事
    • IS会在你有一个带有逗号的标题的那一刻失败
    • 这是完全未经测试的!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多