與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.IO
和System.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");
}
}
'什麼.File'property?那是什麼? –
你可以發佈你的用途? –
'File'是'System.IO'命名空間內的**類**([msdn link](http://msdn.microsoft.com/zh-cn/library/system.io.file.aspx)) 。 – Styxxy