问题描述
这段代码直接粘贴到cs文件中,
This piece of code directly pasted on cs file,
using System;
using System.IO;
namespace csharp_station.howto
{
class TextFileReader
{
static void Main(string[] args)
{
// create reader & open file
TextReader tr = new StreamReader("date.txt");
// read a line of text
Console.WriteLine(tr.ReadLine());
// close the stream
tr.Close();
}
}
}
给我一个错误找不到类型或参考文本阅读器,缺少指令或参考".
我注意到在解决方案资源管理器中,References上没有System.IO.我该如何添加呢?是的,我是VS ...的菜鸟.
give me one of those errors ''type or reference textreader not found, missing directive or reference''.
I noticed that in solution explorer, System.IO is not present on References. how could I add it? Yes, I''m a noob working with VS...
What could be the problem?
推荐答案
Textreader tr = new StreamReader("date.txt");
与
with
StreamReader tr = new StreamReader("date.txt");
顺便说一句,在任何情况下都不应该使用硬代码文件名,绝对没有相对路径.您是否知道此代码取决于工作目录,而工作目录取决于用户如何运行您的应用程序?
所有路径应在运行时根据您的某些配置文件数据的输入程序集位置进行计算.或者,您可以通过文件对话框从用户那里获得文件路径.
By the way, there no situations when hard-code file names should be used, neither absolute no relative paths. Do you know that this code depends on the working directory which depends on how the user runs your application?
All paths should be calculated during run time based on your entry assembly location of some configuration file data. Alternatively, you get file paths form the user via file dialogs.
try
{
string line = null;
System.IO.TextReader readFile = new StreamReader("C:\\date.txt");
line = readFile.ReadToEnd();
Console.WriteLine(line);
Console.ReadLine();
readFile.Close();
readFile = null;
}
catch (IOException ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
这篇关于使用Textreader读取文本文件时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!