不能使用StreamReader方法

不能使用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"; 
+0

现在,它说:“\t指针,并可以仅在不安全的使用固定大小的缓冲区上下文“。”和“参数1:不能从'字符串'转换为'System.IO.Stream'” – Dimsn

+0

你可以显示你的代码示例吗? –

+0

public static string filename =“razpisanie.txt”; TextReader fi =新的StreamReader(文件名);短n = fi.ReadLine();//那么我会使用这个和其他变量从这个文本文件到我的程序。我不必为此有一个方法。它说:“参数1:不能从'字符串'转换为'System.IO.Stream'” – Dimsn

这是一个编译时错误。将您的代码移到方法体中。变化来自:

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 
    } 

} 
+0

但如果我不想使用方法呢? – Dimsn

+0

@Dimsn你是什么意思的“不想使用方法”?那么你在哪里试图把你的代码?你能否提供一些你的代码的例子? – romanoza

+0

public static string filename =“razpisanie.txt”; TextReader fi = new StreamReader(filename);短n = fi.ReadLine();//那么我会使用这个和其他变量从这个文本文件到我的程序。我不必为此有一个方法。它说“参数1:不能从'字符串'转换为'System.IO.Stream'” – Dimsn