2010-07-14 110 views
1

得到这个错误,当我提交表单savetext.aspx操作文件:CS0120:一个对象引用必须

Compiler Error Message: CS0120: An object reference is required for the nonstatic field, method, or property 'System.Web.UI.Page.Request.get' 

在此行中:

string path = "/txtfiles/" + Request.Form["file_name"]; 

整个代码:

<%@ Page Language="C#" %> 
<%@ Import Namespace="System" %> 
<%@ Import Namespace="System.IO" %> 

<script runat="server"> 

class Test 
{ 
    public static void Main() 
    { 
     string path = "/txtfiles/" + Request.Form["file_name"]; 
     if (!File.Exists(path)) 
     { 
      using (StreamWriter sw = File.CreateText(path)) 
      { 
       sw.WriteLine(request.form["seatsArray"]); 
      sw.WriteLine(""); 
      } 
     } 

     using (StreamReader sr = File.OpenText(path)) 
     { 
      string s = ""; 
      while ((s = sr.ReadLine()) != null) 
      { 
       Console.WriteLine(s); 
      } 
     } 
    } 
} 
</script> 

我该如何解决?

谢谢!

+4

'公共静态无效Main()'在一个ASPX页?!嗯...也许你应该解释一下你正在尝试做什么,因为我感觉到这个部队的干扰。 – 2010-07-14 14:50:14

+0

难道你不需要 <%@ Import Namespace =“System.Web.UI.Page”%> – MikeTWebb 2010-07-14 14:51:17

+0

@MikeTWebb,不,他不会。 – 2010-07-14 14:52:21

回答

5

删除此Test类以及静态Main方法,并用Page_Load实例方法,像这样替换它:

<%@ Page Language="C#" %> 
<%@ Import Namespace="System" %> 
<%@ Import Namespace="System.IO" %> 

<script runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     string path = "/txtfiles/" + Request.Form["file_name"]; 
     if (!File.Exists(path)) 
     { 
      using (StreamWriter sw = File.CreateText(path)) 
      { 
       sw.WriteLine(Request.Form["seatsArray"]); 
       sw.WriteLine(""); 
      } 
     } 

     using (StreamReader sr = File.OpenText(path)) 
     { 
      string s = ""; 
      while ((s = sr.ReadLine()) != null) 
      { 
       Response.Write(s); 
      } 
     } 
    } 
</script> 

而且你可能想输出到HttpResponse对象,而不是一个控制台在Web应用程序。另一种说法是关于你的文件路径:"/txtfiles/",NTFS通常不喜欢这种模式。

+0

完美,谢谢。将在“4分钟”内接受答案! – IceDragon 2010-07-14 14:59:38

1

达林季米特洛夫给你一个正确的方向提示,但我只想给问题回答为什么发生这种错误。正常的错误应该是:

The name 'Request' does not exist in the current context

这对每个aspx文件中的类创建默认情况下从Page因继承发生。 aspx文件中定义的所有新类都将成为该类的嵌套类。 Request是类Page的成员,并且发生此特定错误是因为您尝试从嵌套类型的静态方法访问它。

相关问题