不能使用StreamReader方法
问题描述:
我想用StreamReader方法读取文本文件,但它不起作用。我研究所有主题和论坛,但解决方案不适用于我的项目。我的文本文件在C /用户/用户/文件/ VS15 /项目/ MyProject的/ 这里不能使用StreamReader方法
string filename = "text.txt";
TextReader fi = new StreamReader(filename);
我得到这个错误:
" A field initializer cannot reference the non-static field, method, or property 'MainPage.filename' "
是什么原因造成这个错误?
答
尝试过把它的方法,例如:
static void Main(string[] args)
{
string filename = "text.txt";
TextReader fi = new StreamReader(filename);
}
或让你的静态变量:
public static string filename = "text.txt";
答
这是一个编译时错误。将您的代码移到方法体中。变化来自:
class C {
string filename = "text.txt";
TextReader fi = new StreamReader(filename);
private void myMethod() {
// ....
}
}
到:
class C {
string filename = "text.txt";
private void myMethod() {
TextReader fi = new StreamReader(filename);
// ....
}
}
或将代码放在构造函数:
class C {
string filename = "text.txt";
TextReader fi;
public C() {
fi = new StreamReader(filename);
}
private void myMethod() {
// you can use the fi variable here
}
}
现在,它说:“\t指针,并可以仅在不安全的使用固定大小的缓冲区上下文“。”和“参数1:不能从'字符串'转换为'System.IO.Stream'” – Dimsn
你可以显示你的代码示例吗? –
public static string filename =“razpisanie.txt”; TextReader fi =新的StreamReader(文件名);短n = fi.ReadLine();//那么我会使用这个和其他变量从这个文本文件到我的程序。我不必为此有一个方法。它说:“参数1:不能从'字符串'转换为'System.IO.Stream'” – Dimsn