2014-02-27 33 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:谢谢亲爱的:) –