Reputation: 1720
A question relating to ASP.NET (4.5.1) MVC 4. I want to create a file and write a line into that file. To my understanding this is very easy i just do the following:
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);
}
}
}
But when i call the File class it won't work. It does not know the methods Exists, CreateText.
I don't understand it i did import System.IO
. So what is the problem?
UPDATE
Found the solution in my project i imported System.IO
and System.Web.MVC
.
The solution is to call the File class with the full path like so:
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");
}
}
Upvotes: 0
Views: 2108
Reputation: 26209
Problem : I suspect that you have different class in your Project with the name of File
.
so it is referring to that File
instead of System.IO.File
.
Solution : i'd suggest you to use fully qualified namespace to access the File
class from System.IO
to avoid the ambiguity as below:
if(!System.IO.File.Exists("path"))
{
}
Upvotes: 3