2010-07-14 45 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的成員,並且發生此特定錯誤是因爲您嘗試從嵌套類型的靜態方法訪問它。

相關問題