2014-02-27 62 views
0

與ASP.NET(4.5.1)MVC 4有關的問題。我想創建一個文件並在該文件中寫入一行。據我瞭解,這是很容易的,我只是做到以下幾點:文件類無法識別Exists或CreateText方法

public static void Main() 
{ 
    string path = @"c:\temp\MyTest.txt"; 

    if (!File.Exists(path)) 
    { 
     // Create a file to write to. 
     using (StreamWriter sw = File.CreateText(path)) 
     { 
      sw.WriteLine("Hello"); 
      sw.WriteLine("And"); 
      sw.WriteLine("Welcome"); 
     } 
    } 

    // Open the file to read from. 
    using (StreamReader sr = File.OpenText(path)) 
    { 
     string s = ""; 

     while ((s = sr.ReadLine()) != null) 
     { 
      Console.WriteLine(s); 
     } 
    } 
}  

但是,當我打電話File類,它不會工作。它不知道方法Exists,CreateText。 我不明白,我沒有輸入System.IO。那麼問題是什麼?

UPDATE

發現在我的項目的解決方案我進口System.IOSystem.Web.MVC。 的解決方法是調用File類的完整路徑,像這樣:

if (!System.IO.File.Exists(path)) 
    { 
     // Create a file to write to. 
     using (StreamWriter sw = System.IO.File.CreateText(path)) 
     { 
      sw.WriteLine("Hello"); 
      sw.WriteLine("And"); 
      sw.WriteLine("Welcome"); 
     } 
    } 
+2

'什麼.File'property?那是什麼? –

+0

你可以發佈你的用途? –

+0

'File'是'System.IO'命名空間內的**類**([msdn link](http://msdn.microsoft.com/zh-cn/library/system.io.file.aspx)) 。 – Styxxy

回答

1

問題:我懷疑你用的File名稱的項目有不同的類。 所以它指的是File而不是System.IO.File

解決方案:我建議你使用完全合格的命名空間來從System.IO訪問File類,以避免如下歧義:

if(!System.IO.File.Exists("path")) 
{ 


} 
+0

剛剛添加找到答案。但是你第一個發佈正確的答案。所以我會標記它是正確的。 – Msmit1993

+0

@ Msmit1993:謝謝親愛的:) –