【发布时间】: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